You are actually reducing the allocated space, not increasing it. Both malloc
and realloc
take the size in bytes that you want to allocate / resize. And
the size in bytes for an int
is size * sizeof(int)
.
You realloc
call should look like this:
int *tmp = realloc(arr, size_arr * sizeof *tmp);
if(tmp == NULL)
{
fprintf(stderr, "Not enough memory\n");
// arr is left intact, the memory is still allocated
// Error handling, for example
free(arr);
return 0;
}
arr = tmp;
now you have space for size_arr
integers.
Note that is a good practice to use a temp variable for storing the result of
realloc
. When realloc
fails, the original memory is not freed, so if you
don't use a temp variable, then you are losing the pointer to the orginal
memory.
Also, don't cast malloc
and realloc
.