【问题标题】:Why a segmentation fault here?为什么这里出现分段错误?
【发布时间】:2014-03-07 16:37:30
【问题描述】:

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

【问题讨论】:

  • 为什么不设置远程调试?
  • 如果没有看到VertexPointer *graph 是如何创建的,就无法回答这个问题。没有人知道您发布的代码中的图表指向什么。
  • @Daniel Daranas 我发布了更多代码。
  • @hannah 暗示信息似乎不足以提供答案。
  • @tesseract - 不,graph 是一个指向 vertex 的指针; graph[0] 是指向 vertex 的指针; (*graph[0])vertex。那么有什么是正确的。

标签: c arrays segmentation-fault


【解决方案1】:

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

另一个问题是您将2*i 输入错误为2i

第三个问题是,仅仅交换键不足以让算法得到正确的结果,你必须交换整个顶点(或者实际上是它们的指针)。

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 2013-01-29
    • 2019-04-17
    • 2021-09-08
    • 2020-08-03
    • 2012-03-25
    相关资源
    最近更新 更多