1

我有两段代码:

gb_Graph = (int **)malloc(sizeof(int*)*gb_nVertices);


if (gb_Graph == NULL)
    return false;


gb_Open = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Open == NULL)
    return false;


gb_Close = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Close == NULL)
    return false;


for (i = 0; i < gb_nVertices; i++)
{
    gb_Graph[i] = (int*)malloc(sizeof(int)*gb_nVertices);

    if (gb_Graph[i] == NULL)
        return false;

    for (j = 0; j<gb_nVertices; j++)
        fscanf(gb_fInput, "%d", &(gb_Graph[i][j]));
}


for (i = 0 ; i<gb_nVertices; i++)
{
    gb_Open[i].Exist = false;
    gb_Open[i].ParentName = -1;
    gb_Open[i].CostPath = 0;
    fscanf(gb_fInput, "%d", &(gb_Open[i].CostHeuristic));

    gb_Close[i].Exist = false;
    gb_Close[i].ParentName = -1;
    gb_Close[i].CostPath = 0;
    gb_Close[i].CostHeuristic = gb_Open[i].CostHeuristic;
}

gb_Open[gb_nStart].Exist = true;

gb_Graph = (int **)malloc(sizeof(int*)*gb_nVertices);
if (gb_Graph == NULL)
    return false;


for (i = 0; i < gb_nVertices; i++)
{
    gb_Graph[i] = (int*)malloc(sizeof(int)*gb_nVertices);

    if (gb_Graph[i] == NULL)
        return false;

    for (j = 0; j<gb_nVertices; j++)
        fscanf(gb_fInput, "%d", &(gb_Graph[i][j]));
}


gb_Open = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Open == NULL)
    return false;


gb_Close = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Close == NULL)
    return false;


for (i = 0 ; i<gb_nVertices; i++)
{
    gb_Open[i].Exist = false;
    gb_Open[i].ParentName = -1;
    gb_Open[i].CostPath = 0;
    fscanf(gb_fInput, "%d", &(gb_Open[i].CostHeuristic));

    gb_Close[i].Exist = false;
    gb_Close[i].ParentName = -1;
    gb_Close[i].CostPath = 0;
    gb_Close[i].CostHeuristic = gb_Open[i].CostHeuristic;
}

gb_Open[gb_nStart].Exist = true;

在第一个代码中,它会导致错误。如果我在 2 个代码中从文件读取值到 gb_Graph 变量后放置一个断点,则没有区别。但在那之后,在 gb_Open[gb_nStart].Exist = true; ,在第一个代码中,gb_Graph 的值被修改。

我认为这是内存分配的顺序。正确的?

带变量:

VERTEX *gb_Open;    
VERTEX *gb_Close;       
int **gb_Graph;         

请解释一下为什么会出错?我使用 VS C++ 2012

4

1 回答 1

5

这些都是错误的:

gb_Open = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Open == NULL)
    return false;

gb_Close = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Close == NULL)
    return false;

您正在为 分配空间gb_nVertices * sizeof(VERTEX*),也就是说,为gb_nVertices 指针分配空间。您想要sizeof(VERTEX),并且为了安全起见,使用语法取消引用:

gb_Open = malloc(sizeof(*gb_Open)*gb_nVertices);
if (gb_Open == NULL)
    return false;

gb_Close = malloc(sizeof(*gb_Close)*gb_nVertices);
if (gb_Close == NULL)
    return false;

第二个代码块也存在同样的问题。

另请注意,不要将结果转换为malloc()in C

于 2013-10-20T06:36:21.577 回答