5

我用 malloc 在 C 中创建了一个动态数组,即:

myCharArray = (char *) malloc(16);

现在,如果我制作这样的函数并传递myCharArray给它:

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

那会起作用吗,还是我会以某种方式只释放指针的副本myCharArrayp而不是实际的myCharArray

4

3 回答 3

14

您需要了解指针只是一个变量,它存储在堆栈中。它指向一个内存区域,在这种情况下,分配在堆上。您的代码正确地释放了堆上的内存。当您从函数返回时,指针变量与任何其他变量(例如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.
于 2011-03-18T09:55:06.373 回答
9

这会很好,并按照您的预期释放内存。

我会考虑以这种方式编写函数:

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

以便指针在被释放后设置为 NULL。重用以前释放的指针是错误的常见来源。

于 2011-03-18T09:54:29.067 回答
1

是的,它会起作用。

尽管将发送您的指针变量的副本,但它仍将引用正确的内存位置,该位置确实会在调用 free 时释放。

于 2011-03-18T09:55:20.653 回答