I have a little piece of code (in C) where I'am allocating an array and scaning numbers in it. If the array is too small I'm reallocating memory for my array. Sometimes it works fine but sometimes it returns "Error in `./a.out': free(): invalid next size (normal)."
Here is the code:
int *array;
int memory=0, i=0, scanreturn=0;
array = (int *)calloc(30, sizeof(int));
/*Allocating 30 ints*/
while ( scanf("%d", &array[i]) != EOF){
if(i == (memory - 5)){
/*There's only 5 ints left. Allocating 10 more*/
memory = memory + 10;
array = (realloc(array, memory * sizeof *array));
}
i++;
}
...
free(array);
I suppose it's cause freeing the memory at the end but I really don't know how to figure it out.
Looking at your posted code,
If you initialize
memory
correctly, the purpose of usingwould've been served. Change the line
to
to solve the problem.