简体   繁体   中英

malloc() error after initializing a dynamically allocated array

I am trying to call malloc again after initializing another dynamically allocated array, but my program fails to run (though it can pass the compilation). Part of my code is as follows.

table = (Node **)malloc(m * sizeof(Node*));

for(i=0; i<=m; i++)
  table[i] = NULL;

table2 = (Node *)malloc(n * sizeof(Node));

The error information is like:

malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)
->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_si
ze == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (st
ruct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t
))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' 
failed.

The weirdest thing is that I have found that my program can run successfully after removing the second & third lines in my code above, in which NULL is assigned to table[i] . I am a little confused because I don't know what causes this malloc error. In addition, is it proper to assign NULL to newly allocated pointers?

Thanks!

Isn't i<=m in the for loop going to go outside the region you allocated in the first malloc() call? You allocated m Node pointers in your table, and then set m+1 entries equal to NULL .

for(i=0; i<=m; i++)
  table[i] = NULL;

The second expression needs to be changed to i < m . You've allocated m slots. The range of access is 0...(m-1)

table , size = 3

+---+---+---+
| 0 | 1 | 2 |
+---+---+---+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM