为什么这里有分割错误

为什么这里有分割错误

GDB给我以下信息:

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

作为参考,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);
    }
}

最佳答案

崩溃的可能原因在于索引调整:第一次,您将i1调整为0。但是,在随后的通话中,您无法再次向上调整,例如如果i是第一次最小的元素,则第二个调用具有i = -1。该调整代码使您很难推理算法的正确性。

另一个问题是您将2*i键入为2i

第三个问题是,仅交换键以使算法无法提供正确的结果是不够的,您必须交换整个顶点(或实际上是它们的指针)。

关于c - 为什么这里有分割错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22255645/

10-12 16:39