How to use realloc in a function in C

You want to modify the value of an int* (your array) so need to pass a pointer to it into your increase function:

void increase(int** data)
{
    *data = realloc(*data, 5 * sizeof int);
}

Calling code would then look like:

int *data = malloc(4 * sizeof *data);
/* do stuff with data */
increase(&data);
/* more stuff */
free(data);

Both code are very problematic, if you use the same pointer to send and receive from realloc, if it fails, you will lose your pointer to free it later.

you should do some thing like this :

{ ... ...

more = realloc(area , size);
if( more == NULL )
    free(area);
else
    area=more;

... ...

}


Keep in mind the difference between a pointer and an array.
An array is a chuck of memory in the stack, and that's all.If you have an array:

int arr[100];

Then arr is an address of memory, but also &arr is an adress of memory, and that address of memory is constant, not stored in any location.So you cannot say arr=NULL, since arr is not a variable that points to something.It's just a symbolic address: the address of where the array starts.Instead a pointer has it's own memory and can point to memory addresses.

It's enough that you change int[] to int*.
Also, variables are passed by copy so you need to pass an int** to the function.

About how using realloc, all the didactic examples include this:

  1. Use realloc;
  2. Check if it's NULL.In this case use perror and exit the program;
  3. If it's not NULL use the memory allocated;
  4. Free the memory when you don't need it anymore.

So that would be a nice example:

int* chuck= (int*) realloc (NULL, 10*sizeof(int)); // Acts like malloc,
              // casting is optional but I'd suggest it for readability
assert(chuck);
for(unsigned int i=0; i<10; i++)
{
    chunk[i]=i*10;
    printf("%d",chunk[i]);
}
free(chunk);

Tags:

C

Arrays

Malloc