簡體   English   中英

釋放非 malloc 的 memory

[英]Freeing non-malloc'd memory

假設我聲明了以下數組:

char *arr[3];

在運行程序期間,根據用戶的輸入,我可能會也可能不會將 memory 字符串分配到這個數組中(意思是arr[i] )。

在程序結束時free(arr[i])是否安全而不檢查我分配了哪些? 或者這會導致錯誤嗎?

謝謝!

將 null 指針傳遞給free是安全的,因此如果您的數組是使用 null 指針初始化的,您可以安全地釋放所有arr[i] ,假設您只存儲由malloc()和朋友返回的指針,而不是在其他地方釋放它們。

將數組定義為

char *arr[3] = { NULL, NULL, NULL };

或者干脆

char *arr[3] = { 0 };

NULL , 0'\0'可用於指定 null 指針,但建議遵循簡單的清晰規則:

  • 使用NULL作為 null 指針,
  • 使用0表示 null integer,
  • 使用'\0'表示char數組中的 null 字節,也稱為 null 終止符。

你可以使用= { 0 }; 作為任何 C object 的初始化器:所有元素和成員都將被初始化為其類型的零值,但只有第一個成員以這種方式初始化的聯合除外。

The only safe values to pass to free are null pointers and values returned by malloc , and to be clear on that, those values returned by malloc shall only be free d once until next time they're returned by malloc (or calloc , or realloc )。

暫無
暫無

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

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