Hello,
Suppose I dynamically create memory for an array in an external function. When using free later, I'm not sure if I should just use free once on the entire array object, or if I am supposed to iterate through the array an free each element. Or if I am supposed to do something else entirely.
Version 1:
Code:
int * array_malloc_internal(int size) {
int *result = (int*)malloc(size * sizeof(int));
return result;
}
int main( int argc, char* argv[] ) {
int SIZE = 5;
int *my_array = array_malloc_internal(SIZE);
free(my_array);
return 0;
}
Version 2:
Code:
int * array_malloc_internal(int size) {
int *result = (int*)malloc(size * sizeof(int));
return result;
}
int main( int argc, char* argv[] ) {
int SIZE = 5;
int *my_array = array_malloc_internal(SIZE);
for (int i = 0; i < SIZE; i++) {
free(my_array[i]);
}
return 0;
}
I know the external function is not "doing anything" other than allocating memory. I'm trying to use the most basic example possible, because it is the proper freeing of the array I am interested in. I'm guessing it's the first one. The first one has a one free for every one malloc. And my_array inside of main is probably thought of as one big data space in memory once the helper function was called and returned. So the program probably knows to free the entire space of the array. But I could be wrong.
Thank you.