【问题标题】:Expanding array (few times) using realloc - crashes使用 realloc 扩展数组(几次) - 崩溃
【发布时间】:2013-03-26 17:27:05
【问题描述】:
int Add_Edge_To_Vertex(int vertexFromId,int vertexToId){
    vertex vertexTo=vertices[vertexToId];
    if(vertexTo.edgesInArrLength == vertexTo.numOfEdgesIn){ //multiply this vertex arr of edges if needed
        vertices[vertexToId].edgesInArrLength = (vertices[vertexToId].edgesInArrLength)*2;
        tmpVertexEdges = (edge*)realloc((vertices[vertexToId].edges),(vertices[vertexToId].edgesInArrLength)*sizeof(edge));
        if(tmpVertexEdges != NULL) {
            vertices[vertexToId].edges = tmpVertexEdges;
        }
        else
        {
            free(tmpVertexEdges);
            return 0;
        }
    }
}

typedef struct vertex
{
    char* name; //not unique
    int id; //unique
    edge* edges; //array  edges
    int outDegree;
    int edgesInArrLength;
    int numOfEdgesIn;
    double rank;
}vertex;

这就是我初始化顶点的方式-

vertex res={(char *)malloc(strlen(name)*sizeof(char)),verticesCount,(edge*)calloc(1, sizeof(edge)),0,1,0,1};

当边缘是这个结构时-

typedef struct edge
{
    int fromVertexId;
    int toVertexId;
    double weight;
}edge;

当我尝试将 vertex.edges 数组加倍(第 3-12 行)时,程序在 realloc 部分崩溃并显示此错误消息 - * 检测到 glibc /home/froike/workspaceC/Page Ranking/Debug/Page Ranking: malloc(): memory corruption: 0x00000000009711d0 **

【问题讨论】:

  • 如果这是 C++,你为什么不使用std::vectors?如果是 C,你为什么要返回 realloc
  • 您可能在其他地方覆盖edges,并在 realloc 时出现分段错误。
  • 我现在正确添加了您的“编辑”。请删除您的“答案”
  • 这是给 C 的。我试过没有强制转换——同样的问题。我投了回报,所以我可以替换旧的“vertices[vertexToId].edges”。我不认为我会覆盖边缘,因为我只使用它来加倍(像这里)或向这个边缘数组添加另一个边缘

标签: c


【解决方案1】:

我猜你没有初始化struct vertex 中的edges 指针,所以realloc 调用试图重新分配一个无效的指针?但由于你没有给我们所有的代码,我不能确定。

【讨论】:

    猜你喜欢
    • 2013-02-11
    • 2013-06-11
    • 2012-02-16
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多