[英]how to properly free memory in main that is allocated in a function through pointer passed by reference or by pointer?
[英]Free allocated pointer passed to a function?
如果需要將未簽名的char *傳遞給函數,什么時候應該釋放我的未簽名的char *? 例
void myFunction(unsigned char *request){
// do I need to use free(request); here?
}
int main (){
// main code
unsigned char *request = NULL;
// read from buffer and reallocate memory (using realloc & memcpy)
myFunction(request); // I do not want to read or use "request" after this function call.
free(request); // is this ok? Or should this be inside myFunction also?
return 0;
}
完成使用后,立即對某物使用free()
。 因此,例如,您可能不會在myFunction()
執行此操作,因為當您將該函數返回給main
時,您可能仍然會對request
指向的值感興趣。
通常,您必須在分配它的位置釋放它,而不需要更多它。 在這種情況下,您可以在兩個地方都可以執行此操作,也可以在釋放后將其設置為NULL,並且下次嘗試釋放它時,請檢查是否為null
你也可以實現類似的東西:
void FreeAndNull(void *request){
if request <> NULL then
{ free(request); request = NULL; }
}
您不必執行此操作-但一個好的做法是在分配內容的同時釋放它們。 例如,不要在函數中分配某些東西並在返回后釋放它。 因為那樣,幾個月后再次查看代碼時,內存的生命周期就變得不清楚。
因此,執行以下操作要好得多:
request = malloc();
doStuff( request );
free( request );
比你所擁有的模式。 C ++通過創建構造函數和析構函數來幫助您使用此模式。 也就是說,構造函數實際上可能會分配內存,並實質上以對象的形式將其返回給您,但是編譯器會為您釋放內存而自動調用析構函數。
因此,如果將請求緩沖區包裝在類中,則可以使用更安全,更可維護的模式來實現所需的模式,例如:
Request::Request() { mRequest = malloc(); }
Request::~Request() { if ( mRequest ) free( mRequest ); mRequest = NULL; }
...
{
Request request;
myFunction( request );
}
使用此模式,您的內存將自動清除。 更安全,更易維護。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.