簡體   English   中英

如何在C中的結構內的衣衫matrix的矩陣上修復不穩定的free()調用

[英]How to fix unstable free() call on a ragged matrix inside a struct in C

我正在創建一個n * m尺寸的地圖,應該從文件輸入中獲取。 地圖的每個位置都對距離計數很重要。 在整個執行周期中,我經歷了4個malloc()調用,但是我無法將它們與4個free()調用進行匹配,否則執行可能會或可能不會結束,我也不明白為什么。

這是主要電話:

int main()
{
    map_t newMap;
    newMap = map_create(30, 30);

    //there's some test calls that I'm ommiting as they simply work and don't matter

    map_destroy(newMap);
    return 0;
}

據我所知,並且我想要的map_t是指向結構的指針,它是在頭文件上定義的,如下所示:

typedef struct map *map_t;

它的實現是在相應的.c文件中進行封裝的。 這是此案例的實現和重要功能:

struct map{
    position_t **positions;
    int lines, columns;
};

map_t map_create(int n, int m)
{
    map_t newMap = malloc(sizeof(map_t));

    newMap->lines = n;
    newMap->columns = m;

    newMap->positions = malloc(n * sizeof(position_t*));
    int i;
    int k;
    for(i = 0; i < n; ++i)
    {
        newMap->positions[i] = malloc(m * sizeof(position_t));
        for(k = 0; k < m; ++k)
        {
            newMap->positions[i][k] = position_create();
        }
    }

    return newMap;
}

void map_destroy(map_t map_p)
{
    int i, k;
    int n = map_p->lines;
    int m = map_p->columns;
    for(i=0; i < n; ++i)
    {
        for(k=0; k < m; ++k)
        {
            position_destroy(map_p->positions[i][k]);
        }
        free(map_p->positions[i]);
    }

    free(map_p->positions);

    free(map_p);
}

為了完整起見,這是特定於位置結構的代碼,它遵循與地圖結構相同的思想。

typedef struct position *position_t; //this is on the .h, the rest is on the .c file

struct position{
    int has_treasure;
    int times_visited;
};

position_t position_create()
{
    position_t newPosition = malloc(sizeof *newPosition);
    newPosition->has_treasure = YES;
    newPosition->times_visited = 0;

    return newPosition;
}

void position_destroy(position_t position_p)
{
    free(position_p);
}

我已經確定了造成該問題的免費電話,但我不明白為什么。 如果我評論以下兩行:

free(map_p->positions);
free(map_p);

一切正常。 我已經看到了分配初始內存的不同方法,例如這種方法- 如何在C中正確設置,訪問和釋放多維數組? -但是即使找到了各種解決方案,我仍然會得到同樣的不穩定。

這可能非常簡單,我只是忽略了一些東西,已經進行了5天,即使我必須實施一個我至少想了解的解決方案,我也不想在此混亂中借用別人的時間。怎么了。

代碼不會使用-Wall -g -c產生任何警告,如果添加-pedantic,我只會收到有關注釋的投訴。

提前加油

編輯:更改position_t newPosition = malloc(sizeof(position_t)); position_t newPosition = malloc(sizeof *newPosition); 行為還是一樣

EDIT2:在map_t malloc上執行了更改的確切類型,問題解決了,我一直以為問題在**positions

第一個malloc(sizeof(map_t)); 僅為指針分配空間。 您需要使用malloc(sizeof(*map_t));

但我知道,您已經發現了。

暫無
暫無

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

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