0
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/页面排名/调试/页面排名:malloc():内存损坏:0x00000000009711d0 * *

4

1 回答 1

1

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

于 2013-03-26T08:52:36.097 回答