C中的内存分配顺序导致写入变量错误?

时间:2013-10-20 06:27:04

标签: c

我有两段代码:

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

1 个答案:

答案 0 :(得分: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;

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

另请注意,don't cast the result of malloc() in C