[ACCEPTED]-How to free a pointer to a dynamic array in C?-dynamic-arrays

Accepted answer
Score: 14

You need to understand that a pointer is 7 only a variable, which is stored on the 6 stack. It points to an area of memory, in 5 this case, allocated on the heap. Your code 4 correctly frees the memory on the heap. When 3 you return from your function, the pointer 2 variable, like any other variable (e.g. an 1 int), is freed.

void myFunction()
{
    char *myPointer;     // <- the function's stack frame is set up with space for...
    int myOtherVariable; // <- ... these two variables

    myPointer = malloc(123); // <- some memory is allocated on the heap and your pointer points to it

    free(myPointer); // <- the memory on the heap is deallocated

} // <- the two local variables myPointer and myOtherVariable are freed as the function returns.
Score: 9

That will be fine and free the memory as 5 you expect.

I would consider writing the 4 function this way:

 void reset(char** myPointer) {
     if (myPointer) {
         free(*myPointer);
         *myPointer = NULL;
     }
 }

so that the pointer is 3 set to NULL after being freed. Reusing 2 previously freed pointers is a common source 1 of errors.

Score: 1

Yes it will work.

Though a copy of your pointer 3 variable will be sent, but it will still 2 refer to the correct memory location which 1 will indeed be released when calling free.

More Related questions