c - 为什么这里会出现段错误?

标签 c arrays segmentation-fault

GDB 为我提供以下信息:

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

作为引用,图表是一个指针数组。

//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

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

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

相关文章:

c - 绑定(bind)和套接字编程

c - 获取每个文件行的整数个数

c - 为什么文件的字符数相同时文件大小不同?

javascript - 按共同值(value)观分组

c - 段错误和信号量无法正常工作

php - 使用 SplObjectStorage 序列化对象树时出错

c++ - 如果进程崩溃,映射文件会怎样?

java - 如何访问数组的通用数组列表中的元素

python - 在 Python 中关联两个 3D 数组

c - 双重释放或损坏 (!prev) 中止(核心转储) C 语言错误