2013-03-26 54 views
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-擴大使用數組(幾次)realloc的 - 崩潰

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

邊緣時,這是struct-

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

當我嘗試雙精度up vertex.edges數組(第3-12行),程序在realloc部分崩潰,並顯示此錯誤消息 - * glibc detected /home/fro IKE/workspaceC /網頁排名/調試/網頁排名:malloc()函數:內存破壞:0x00000000009711d0 * *

+0

這是C還是C++? – 2013-03-26 08:51:38

+3

如果這是C++,爲什麼不使用'std :: vector's?如果它是C,你爲什麼要拋出'realloc'的返回? – Mat 2013-03-26 08:54:06

+0

您可能會在其他地方覆蓋'edges',並在_realloc_時出現分段錯誤。 – Rohan 2013-03-26 08:55:28

回答

1

我猜你沒有初始化的edges指針struct vertex等等realloc呼叫嘗試重新分配一個無效的指針?但是,由於你沒有給我們所有的代碼,我不能確定。