I've got a very simple piece of C code that uses malloc and realloc, but it induces a seg fault if I change a value that was part of the first array.
#include <stdlib.h>
void increase(int** array)
{
int * new_array;
new_array = realloc(*array, 10 * sizeof(int));
if (new_array != NULL) {
*array = new_array;
}
else {
// Error in reallocation
}
int i = 3;
*array[i] = 2; // Seg fault if i = 0, 1, 2, 3
}
main()
{
int *array = malloc(4 * sizeof(int));
increase(&array);
free(array);
}
Is my understanding of pointers at fault? Can anyone explain what's happening and how I can use realloc properly?
Many thanks!
You probably need:
(*array)[i] = 2;
The [] operator binds before the *, so your version was doing *(array[i]) which is, well, wrong.