At the end of the code below, which pointer would I need to plug into free(), array or temp_array? Does it matter which one or would either free the memory block?
int *array = 0;
int *temp_array = 0;
int count = 0;
array = malloc(sizeof(int));
// skipping code where count is calculated...
temp_array = realloc(array, count * sizeof(int));
if (temp_array == NULL) {
free(array);
// some error message
return;
}
array = temp_array;
// skipping section of code, which reads numbers from a file and loads them into an array
// amount of numbers read can be 0 to whatever
free (array); // free array or temp_array?
Also, is it possible to allocate a block of memory with realloc if the pointer it's trying to allocate memory for is NULL (in other words, do I need to allocate memory first with malloc and later resize it with realloc, or can I skip the malloc)?
It doesn't matter - both temp_array
and array
point to the same memory block. I would prefer temp_array
as then the realloc and free pointers match. Depending on your working code, for protection you could consider assigning both pointers to NULL to prevent free-ing the memory twice. free(NULL)
is safe - no operation is performed.
Regarding the initial alloc of one integer - is that necessary? From the code shown, an int defined on the stack would be preferable.
EDIT: After more info from OP (in comments) it appears the code can be simplified using an header value which holds the number of records in the file. This eliminates the need for realloc and permits memory allocation prior to reading the file values in.