簡體   English   中英

如果 realloc 返回 NULL 我必須釋放舊內存嗎?

[英]If realloc returns NULL do I have to free old memory?

所以我知道realloc()可以遵循兩種方式。 第一種方法是在新地址中分配內存並釋放舊內存。 第二種方法是在同一地址分配內存,以便您只需要釋放該地址。 所以在這兩種方式中,你只需要釋放realloc()分配的地址。 但是,如果realloc()返回 NULL 會發生什么,我必須像這樣釋放舊內存嗎?

//so in the first way, as b would be another address, a would be freed and if b is NULL it is no necessary to free it. But, if it follows second way, b will be same address as a and if it is NULL, I need to free old memory (a), right? 
int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);

if(!b){
   free(a);
}

如果在此代碼段中

int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);

函數realloc將返回 NULL,那么在這種情況下,早期分配的內存將不會被釋放。

所以在這種情況下程序或函數應該如何表現取決於上下文。 可以釋放之前分配的內存

free( a );

或者考慮到realloc失敗,繼續處理先前分配的內存。

暫無
暫無

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

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