为什么这里出现分段错误?

时间:2014-03-07 16:37:31

标签: c arrays segmentation-fault

GDB向我提供了以下信息:

程序收到信号EXC_BAD_ACCESS,无法访问内存。 原因:KERN_INVALID_ADDRESS位于地址:0x0000000000000000 minHeapify()

中的0x0000000100000a3f

作为参考,graph是一个指针数组。

//all info for a vertex
typedef struct Vertex{
    float key;
    struct Vertex *prev;
    float loc[4];
} Vertex;

//using the pointer
typedef Vertex *VertexPointer;

VertexPointer *
createGraph(int numpoints, int dimension){
    //seed the psuedo-random number generator
    srand(time(NULL));

    //declare an array for the vertices
    VertexPointer *graph = malloc(numpoints * sizeof(*graph));

    //create the vertices in the array
    int x;
    int z;
    for(x = 0; x < numpoints; x++){
        //create the vertex
        VertexPointer v;
        v = (VertexPointer)malloc(sizeof(Vertex));
        (*v).key = 100;
        //(*v).prev = 0;
        //multiple dimensions
        for(z=0; z < dimension; z++){
            (*v).loc[z] = rand_float();
        }
        //put the pointer in the array
        graph[x] = v;
    }
    return graph;
} 


void
extractMin(VertexPointer *graph, int size){
    printf("We've stepped into extractMin");
    (*graph[0]).key = 100;
    minHeapify(graph, size, 1);
}




void
minHeapify(VertexPointer *graph, int size, int i) { 
    printf("We've stepped into minHeapify");
    //get the indexes of the left and right children.  readjust indices to start at 0.
    int l = 2i -1;
    int r = 2i;
    i = i - 1;

    //following the algorithm on p. 154 of CLRS  
    int smallest;
    if((l < size) && ((*graph[l]).key < (*graph[i]).key) ){
        smallest = l;
    }
    else{
        smallest = i;
    }
    if( (r < size) && ((*graph[r]).key < (*graph[smallest]).key) ){
        smallest = r;
    }
    if(smallest != i) {
        float exchange = (*graph[i]).key;
        (*graph[i]).key = (*graph[smallest]).key;
        (*graph[smallest]).key = exchange;
        minHeapify(graph, size, smallest);
    }
}

1 个答案:

答案 0 :(得分:1)

崩溃的可能原因在于您的索引调整:首次,您将i1调整为0。但是,在后续呼叫中,您无法再次向上调整,例如,如果第一次i是最小元素,则第二次调用i = -1。调整代码使得很难推断出算法的正确性。

另一个问题是您将2*i误认为2i

第三个问题是交换算法的密钥以提供正确的结果是不够的,你必须交换整个顶点(或实际上,他们的指针)。