Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
Henrik Avatar asked Mar 18 '11 09:03

Henrik


People also ask

How do pointers help in dynamic allocation?

Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable). integer, 8, stored. The other is the “value” or address of the memory location.

Can you free an array in C?

If the array is declared statically, then we do not need to delete an array since it gets deleted by the end of the program/ block in which it was declared. If the array is declared dynamically, we need to free the memory allocated to it using the free() function.

How do I malloc a dynamic array?

Syntax: ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.


2 Answers

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.
like image 85
Joe Avatar answered Sep 20 '22 03:09

Joe


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.

like image 20
Jeff Foster Avatar answered Sep 18 '22 03:09

Jeff Foster