free a pointer to dynamic array in c

假装没事ソ 提交于 2019-12-07 08:37:18

问题


I create a dynamic array in c with malloc. e.g.:

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 (myCharArrayp) and not the actual myCharArray?


回答1:


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

I'd consider writing a function like

 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 error.




回答2:


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.



回答3:


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.



来源:https://stackoverflow.com/questions/5350314/free-a-pointer-to-dynamic-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!