使用realloc扩展数组(几次) - 崩溃

时间:2013-03-26 08:49:04

标签: c

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};

当edge是这个结构时 -

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():内存损坏:0x00000000009711d0 * * < / p>

1 个答案:

答案 0 :(得分:1)

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