![](/img/trans.png)
[英]Confusion about using malloc/calloc pointer to hold the return value of realloc
[英]Question about decreasing malloc size by using realloc
我正在嘗試減小 malloc 數組的大小,但是當我為 malloc 重新分配一個較小的大小時,它會拋出 -1073741819 (0xC0000005)。
typedef struct {
float reproduce_prob;
int mature;
int life;
int age;
char *direction;
int X;
int Y;
} slug;
slug *slugs = (slug *) malloc(sizeof(slug) * (slugCount + 1));
int slugCount = 0;
if (slugCheck(theGrid, frogs[i])) {
int pos = feedFrog(frogs[i], slugs, slugCount);
for (int z = pos; z < slugCount - 1; z++) {
slugs[z] = slugs[z + 1];
}
slugCount--;
slugs = realloc(slugs, sizeof(slugs) * (slugCount + 1));
frogs[i].initHung = 0;
}
slugCount 不為零。
最好在sizeof
中使用對象而不是類型。 擁有獨特且有意義的類型和變量名稱以避免此類錯誤也很好。 我會調用slug
slugType
或slug_type
。
在這一行中,您沒有分配足夠的空間(假設 slug 結構大於指針),因為 sizeof(slugs) 將指針的大小提供給slug
:
slugs = realloc(slugs, sizeof(slugs) * (slugCount + 1));
您還錯誤地使用了 realloc,因為 realloc 可能會失敗,您將有 memory 泄漏
slug *tmp;
tmp = realloc(slugs, sizeof(*tmp) * (slugCount + 1));
if(tmp)
{
slugs = tmp;
}
else
{
/* error handling */
}
作為旁注:不要malloc
系列函數的結果。 如果你的代碼沒有通過編譯就意味着你使用C++編譯器編譯了C語言代碼。 這不是一個好主意,因為 C 和 C++ 是不同的語言,即使語法看起來相似。
這段代碼如何編譯?
slug *slugs = (slug *) malloc(sizeof(slug) * (slugCount + 1));
int slugCount = 0;
編譯器應該對你大喊大叫,因為你在定義slugCount
之前就使用了它。
如果正在構建此代碼,則意味着您已經在封閉的slugCount
中定義了 slugCount,並且它的值可能不為零。 這是一個問題。
您應該始終檢查malloc
、 calloc
和realloc
的結果。 您確定malloc
和realloc
調用都沒有返回NULL
嗎?
這一行是可疑的:
slugs = realloc(slugs, sizeof(slugs) * (slugCount + 1));
sizeof(slugs)
為您提供指針的大小,而不是slug
類型 - 您沒有將數組擴展一個元素,而是將其縮小了很多。 您可能想將其更改為
slug *tmp = realloc( slugs, sizeof *slugs * (slugCount + 1) );
您應該始終將realloc
的結果分配給一個臨時變量。 realloc
如果不能滿足請求會返回NULL
,並保留原來的buffer 。 但是,如果將NULL
結果分配回原始指針,您將失去對 memory 的唯一引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.