I am getting an error in a huge application that I have when I try to reallocate a 2d int array. Trying to narrow down the problem, I generated a small code only with the reallocations. ERROR :
a.out: malloc.c:3574: mremap_chunk: Assertion ((size + offset) & (mp_.pagesize-1)) == 0' failed.
Aborted.
Relevant code:
int main()
{
int **am=NULL,size=0,ans=0,i;
char **name=NULL;
while(ans!=7)
{
printf("\n\n\t1. Add a Point \n\n\t2.Exit\n\n\t\t Enter your Choice : ");
scanf("%d",&ans);
switch(ans)
{
case 1 :
name=realloc(name,(size+1)*sizeof(char *));
name[size]=realloc(name[size],100*sizeof(char));
printf("\nEnter Name of Point : ");
scanf("%s",name[size]);
am=realloc(am,(size+1)*sizeof(int *));
am[size]=realloc(am[size],(size+1)*sizeof(int)); ``
if(size > 0 && am==NULL)
{
printf("Error : Can not Allocate Memory !");
break;
}
for(i=0;i<=size;i++)
{
if(i!=size)
{
am[size][i]=INFINITE;
am[i][size]=INFINITE;
}
else
am[i][size]=0;
}
size++;
break;
case 2 :
exit(0);
}
}
}
Your first problem is here:
name=realloc(name,(size+1)*sizeof(char *));
name[size]=realloc(name[size],100*sizeof(char));
The memory returned by realloc (NULL,)
is uninitialized. This means that you're passing a random pointer to the second realloc()
. Use malloc()
instead.
The same goes for the second pair of realloc()
calls.
There is another problem here:
for(i=0;i<=size;i++)
{
if(i!=size)
{
am[size][i]=INFINITE;
am[i][size]=INFINITE;
You're accessing am[i][size]
for every am[i]
, but only the last one will actually have that many elements. The amount allocated will grow through every round of the while
loop. You need to rethink your logic.