Search code examples
cpointersmallocrealloc

Realloc an array but do not lose the elements in it


Code:

int * data;
data = malloc(sizeof(int)*10);
int i;
for(i=0;i<10;i++)
  data[i]=i;
int * aux;
aux = realloc(data,sizeof(int)*20);
if(aux)
   data=aux;
for(i=10;i<20;i++)
  data[i]=i;

A teacher once told me "No, you can't reallocate an array with elements without a backup"; I said, "Oh, OK", but now that make no sense to me.

The memory pointed by the pointer is already allocated so is "impossible" to lose it; if I make a safe realloc there should be no problem.

My question is: if I want to resize an dynamic array, is the above example code valid?


Solution

  • It is OK. Just two three more things to make it perfect,

    1. Check for malloc() success before using the returned pointer.
    2. If realloc() fails, you should not be accessing the array with new dimension.
    3. After this code block, it's difficult to find out whether the allocated memory for data has been changed (20) or not (10). So, the better approach is to instead of checking for not-NULL,

      • check for NULL as the returned pointer of realloc()
      • stop/return/abort if it's NULL [ or use the old dimension for further code, if you may]
      • continue with the new dimension otherwise.