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?
It is OK. Just two three more things to make it perfect,
malloc()
success before using the returned pointer.realloc()
fails, you should not be accessing the array with new dimension.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,
realloc()