Reputation: 11
I am presently learning C and am trying to expand the amount of memory available to an array of structures. When I attempt to grow the array I receive the following error at runtime
malloc.c:2852: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed. Aborted.
Here is the code that is causing the problem.
I have tried reading the realloc man page and online tutorials, but have been unable to find anything that addresses this specific case.
typedef struct _hash{
int times;
char word[250];
struct _hash *n;
}Hash;
int main(){
Hash* temp;
int currentMax=10;
Hash* ptr[currentMax];
for(int i=0; i<10;i++){
ptr[i]=malloc(sizeof(ptr));
strcpy(ptr[i]->word, "hello world");
ptr[i]->times=1;
ptr[i]->n=NULL;
}
temp=realloc(ptr, 3*sizeof(Hash));
}
I am expecting the array to expand by a size of three so that I can add additional elements at a later time, but I keep getting the same error.
Upvotes: 1
Views: 764
Reputation: 137448
ptr[i]=malloc(sizeof(ptr));
You're allocating the wrong size here. This should be
ptr[i]=malloc(sizeof(*ptr[i]));
Or
ptr[i]=malloc(sizeof(Hash));
Because of this, you're subsequently overrunning your buffer and invoking undefined behavior.
You should consider compiling your program with -g
(to enable debug symbols), and running it under valgrind
. Errors like this will be immediately identified.
Upvotes: 1