簡體   English   中英

釋放C中零長度數組的已分配內存

[英]Freeing the allocated memory of a zero-length array in C

我今天學到了一個新技巧,包括結束一個帶有零長度數組的結構,以允許該數組根據需要動態調整大小。 這非常方便,當我想確定我的struct在運行時而不是編譯時占用的空間量時,可以節省大量內存。

使用它們完美無缺; 然后我記得我需要釋放我分配的內存,所以我只是扔了一個免費的(struct); 在那里,但令我沮喪的是,這給我一個錯誤:

    *** glibc detected *** ./program: free(): invalid next size (fast): <address>
    ======= Backtrace: =========
     <omitted>
    ======= Memory Map: ========
     <omitted>

這是一個格式不佳的代碼中的簡單示例:

   struct Stuff {
     int size; // defines the amount of bytes the entire struct will take up
     char data[0];
   }

   ...

   // This gives me an int and a char[30].
   struct Stuff *ptr = (struct Stuff *) malloc(sizeof(struct Stuff) + 30); 

   ... 
   doStuff();
   ...

   free(ptr);

我得到了免費的錯誤(ptr);

有任何想法嗎?

你的malloc() / free()代碼沒問題。 要驗證,注釋掉malloc()free()之間的所有內容,看看問題是否消失(我敢打賭)。

你幾乎肯定會在某個地方寫入已分配內存的末尾(可能在doStuff() )。 例如,如果doStuff()使用ptr->size來確定ptr->data的大小, ptr->data確保正確初始化ptr->size

刪除doStuff()以便離開(ptr)並重試。 你有同樣的錯誤嗎?

也許你的代碼在某處改變了ptr值。

使用:

struct Stuff * const ptr = ...

代替:

struct Stuff * ptr = ...

在編譯時檢測這類問題。

也許你在doStuff()中所做的就是使用超過結構頭之外分配的超過30個額外字節。 確保正確計算所需的空間量。

暫無
暫無

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

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