2017-09-03 81 views
-1

我最近開始學習C,並寫一些應用程序,我得到這個錯誤,我從來沒有見過的,當我mallocingC:malloc的斷言失敗

malloc.c:2394: Assertion (old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0) failed. Aborted (core dumped)

下面這顯然我得到的是代碼段

typedef struct { 
    Node *root; 
    pthread_id id; 
    pid_t tid; 
}Thread; 

typedef struct { 
    Thread **thread; 
    int cap, len; 
}arr; 

static __thread Thread *self = NULL; 
pthread_mutex_t lock; 
static arr p; 

static void 
foo (void) 
{ 
    pthread_mutex_lock(&lock); 
    Thread **newthread; 
    if (p.len == p.cap){ 
     if (p.cap != 0){ 
      newthread = (Thread **) realloc(p.thread, (1+p.cap)*sizeof(Thread *)); 
     } 
     else { 
      newthread = (Thread **)malloc(sizeof(Thread *)); 
     } 
     if (!newthread){ 
      printf("appendThreadpointer: Error while allocating size\n"); 
      exit(1); 
     } 
     p.thread=newthread; 
     ++p.cap; 
    } 

    ++p.len; 
    Thread *t = malloc(sizeof(Thread *)); 
    t->tid = syscall(SYS_gettid); 
    t->root = newNode(); 
    t->id = pthread_self(); 
    p.thread[p.len-1] = t; 
    self = t; 
    pthread_mutex_unlock(&lock); 
} 

任何人都可以看到這種情況發生的原因嗎?最奇怪的是,如果我從Thread結構中刪除tid字段,那麼它工作正常,它只給我這個錯誤,當我包含tid字段。

我很困惑,任何幫助,將不勝感激,謝謝。

+3

'主題* T =的malloc(的sizeof(螺紋*));' - 這看起來腥。你爲線程指針分配空間,但是你需要一個線程空間:'Thread * t = malloc(sizeof(Thread));''或者更好,Thread * t = malloc(sizeof(* t));'' 。 (你得到的錯誤可能與下面的分配't'有關,因此稍後寫入越界,你就會破壞動態內存的C庫的household數據。) –

+0

ohh man,這樣一個愚蠢的錯誤,是的,你是對的,非常感謝, – Nik391

回答

0
Thread *t = malloc(sizeof(Thread *)); 

或許應改爲

Thread *t = malloc(sizeof(Thread)); 
+2

養成將malloc寫成'ptr = malloc(sizeof(* ptr))'的習慣會爲你節省很多的痛苦。 (這比'sizeof(Thread)'更好,恕我直言,或者任何ptr聲明爲,因爲如果你改變ptr的存儲類,它仍然是正確的)。 – Jabberwock