簡體   English   中英

關於使用 realloc 減小 malloc 大小的問題

[英]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 slugTypeslug_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,並且它的值可能不為零。 這是一個問題。

您應該始終檢查malloccallocrealloc的結果。 您確定mallocrealloc調用都沒有返回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.

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