【发布时间】: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