Henrik
Henrik

Reputation: 167

How to free a pointer to a dynamic array in C?

I create a dynamic array in C with malloc, ie.:

myCharArray = (char *) malloc(16);

Now if I make a function like this and pass myCharArray to it:

reset(char * myCharArrayp)
{
    free(myCharArrayp);
}

will that work, or will I somehow only free the copy of the pointer to myCharArrayp and not the actual myCharArray?

Upvotes: 5

Views: 40275

Answers (3)

Jeff Foster
Jeff Foster

Reputation: 44746

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

I would consider writing the function this way:

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

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

Upvotes: 9

Joe
Joe

Reputation: 47729

You need to understand that a pointer is only a variable, which is stored on the stack. It points to an area of memory, in this case, allocated on the heap. Your code correctly frees the memory on the heap. When you return from your function, the pointer variable, like any other variable (e.g. an 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.

Upvotes: 14

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22114

Yes it will work.

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

Upvotes: 1

Related Questions