简体   繁体   English

如何在C中释放指向动态数组的指针?

[英]How to free a pointer to a dynamic array in C?

I create a dynamic array in C with malloc, ie.:我用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 to myCharArrayp and not the actual myCharArray ?这会起作用,还是我会以某种方式只释放指向myCharArrayp的指针的副本而不是实际的myCharArray

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 (eg an int ), is freed.当您从函数返回时,指针变量与任何其他变量(例如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.

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.以便指针在被释放后设置为 NULL。 Reusing previously freed pointers is a common source of errors.重用以前释放的指针是常见的错误来源。

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 时确实会被释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM