Mark Z.
Mark Z.

Reputation: 655

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!

Upvotes: 0

Views: 226

Answers (2)

Ryan
Ryan

Reputation: 14649

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 |
+---+---+---+

Upvotes: 1

mshindal
mshindal

Reputation: 588

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.

Upvotes: 5

Related Questions