I would like to resize the array when it reaches its max capacity. But error came up after i do ./a.out Please help me…
Error: a.out: malloc.c:3574: mremap_chunk: Assertion `((size + offset) & (mp_.pagesize-1)) == 0' failed.
code:
#include<stdio.h>
#include <stdlib.h>
int main(void)
{
int cap=5;
int *arr = malloc(cap*sizeof(int));
FILE *f;
if((f=fopen("/home/file.txt","r"))==NULL)
printf("You cannot open");
while(fscanf(f, "%d", arr++)!=EOF)
{
index++;
if(index==cap-1)
arr = realloc(arr, (cap +=1) * sizeof(int));
}
return 0;
}
You have
arr++in your loop condition. That meansarrdoesn’t point to the start of the allocated memory anymore when you callrealloc(). That’s going to end up with the error you’re seeing.Also:
Programming safety note:
Don’t call
realloc()in the form:If an error occurs,
foowill be set toNULLand you’ll leak the original allocation.Nonidiomatic code note:
is a bit weird. Why not
++cap * sizeof(int)? Or better yet, do it on two lines rather than cramming it all into one.