[英]Memory leak - How do I allocate memory for a Typdef Struct passed within another struct as thread arguments?
[英]how do I release a struct from memory and arrays within them
我想知道如何從內存中正確釋放結構並完全擦除它。 我還需要擦除此結構中的數組或值。 每次數據更改時,我都嘗試用新數據覆蓋結構,但是觀察到內存使用量一直在穩定增長,直到收到內存警告,所以我認為最安全的選擇是先完全擦除數據,然后再次寫入。
typedef struct {
SInt16 *array1;
SInt16 *array2;
} myStruct, *myStructPtr;
myStructArray myStruct[16];
for(int i=0;i<16;i++)
{
myStruct[i].array1 =
(AudioUnitSampleType *) calloc (asize, sizeof (SInt16));
myStruct[i].array2 =
(AudioUnitSampleType *) calloc (asize, sizeof (SInt16));
}
free(myStructArray) // throws SIGBART error
您沒有malloc
或calloc
myStructArray
所以您不應該free
它。 循環遍歷元素並free
myStruct[i].array1
和array2
for(int i=0;i<16;i++)
{
free(myStruct[i].array1);
free(myStruct[i].array2);
}
一般規則很簡單- free
您的malloc/calloc/realloc/strdup/other allocs
,不多多少少。 請注意, alloca
是一種豁免-它在堆棧上分配,因此您永遠都不應釋放從中獲得的收益。
myStructArray myStruct[16];
myStruct
是在堆棧上創建的對象的數組。 您不能free
撥打電話。 free
需要被上(使用malloc,realloc的等)從自由存儲區獲得的資源調用。 相反,您需要對結構成員array1
, array2
免費調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.