C语言 在c中释放一个指向动态数组的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5350314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
free a pointer to dynamic array in c
提问by Henrik
I create a dynamic array in c with malloc. e.g.:
我用 malloc 在 c 中创建了一个动态数组。例如:
myCharArray = (char *) malloc(16);
now if I make a function like this and pass myCharArray to it:
现在,如果我创建一个这样的函数并将 myCharArray 传递给它:
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?
这会起作用,还是我会以某种方式只释放指针(myCharArrayp)的副本而不是实际的myCharArray?
回答by Joe
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.
您需要了解指针只是一个变量,它存储在堆栈中。它指向一个内存区域,在这种情况下,分配在堆上。您的代码正确释放了堆上的内存。当您从函数返回时,指针变量与任何其他变量(例如 an int)一样被释放。
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.
回答by Jeff Foster
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.
这样指针在被释放后被设置为NULL。重用以前释放的指针是一个常见的错误来源。
回答by Shamim Hafiz
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.
虽然将发送您的指针变量的副本,但它仍将引用正确的内存位置,该位置在调用 free 时确实会被释放。

