Walter said:
D² said:
I was trying to enlarge the size of an array wqith this code:
float data [100];
data = realloc (data, n*sizeof(float));
You can only realloc() space that was dynamically allocated,
such as via malloc() or alloc() .
The first arguement in function realloc may have a NULL value
which makes the function behave like function malloc for the
requested space. 'data' must have either the value of NULL or
a value previously returned by function malloc, calloc, or
realloc.
In the above realloc statement, it is unwise to assign the
return value of function realloc to 'data'. If the function
returned NULL, 'data' with have that NULL value and the previous
value of 'data' which may have been a pointer to allocated memory
would be lost making the space unaccessible for use
or for freeing the space.
Typically, one will make the allocations as follows.
#include <stdlib.h>
float *data = NULL;
float *tmp;
size_"t n;
n = 15;
tmp = realloc(data,n * sizeof *data);
if(tmp != NULL)
{
data = tmp;
/* use the storage */
}
n = 8;
tmp = realloc(data,n * sizeof *data);
if(tmp != NULL)
{
data = tmp;
/* use the storage */
}
free(data); /* Finished with it */
data = NULL; /* put it back to NULL */