1

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)?

Aelyn
  • 37
  • 1
  • 7

1 Answers1

1

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.

suspectus
  • 16,548
  • 8
  • 49
  • 57
  • I'm not sure if I wrote it the best way, but the code comes from a function which reads integers from a file and loads them into an array. The amount of integers can be 0 to whatever. I did the malloc outside the for loop that loops through the numbers in the file, and inside the for loop I use realloc to increase the size of the array. I wasn't sure if it's possible to allocate memory on a NULL pointer, so that's why I called malloc first. Is it possible to allocate memory using realloc if the pointer is NULL? ie ptr = realloc (NULL, count * sizeof(int)); – Aelyn Jun 23 '14 at 19:36
  • ok. I would create a header in the file containing the number of records. Then the function would first read the header int, allocate sufficient memory then read all the values in. – suspectus Jun 23 '14 at 19:40
  • good - I'll update answer in a minute. BTW please upvote or accept answer if it helps. thanks :) – suspectus Jun 23 '14 at 19:44