簡體   English   中英

如何在C中釋放指向動態數組的指針?

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

我用malloc在C中創建了一個動態數組,即:

myCharArray = (char *) malloc(16);

現在,如果我創建一個這樣的函數並將myCharArray傳遞給它:

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

這會起作用,還是我會以某種方式只釋放指向myCharArrayp的指針的副本而不是實際的myCharArray

您需要了解指針只是一個變量,它存儲在堆棧中。 它指向一個內存區域,在這種情況下,分配在堆上。 您的代碼正確釋放了堆上的內存。 當您從函數返回時,指針變量與任何其他變量(例如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.

這會很好,並按您的預期釋放內存。

我會考慮這樣寫函數:

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

以便指針在被釋放后設置為 NULL。 重用以前釋放的指針是常見的錯誤來源。

是的,它會起作用。

盡管將發送您的指針變量的副本,但它仍將引用正確的內存位置,該位置在調用 free 時確實會被釋放。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM