我有一台struct cell ->
struct cell {
double x, y, h, g, rhs;
struct key *keys;
};我使用下面的方法来释放一个单元格->
void cellFree(struct cell *c) {
// Free the keys
free(c->keys);
// Free the cell itself.
free(c);
}
void cellFreeSors(struct cell *cn) {
int i;
for(i = 0; i < 5; i++) {
// Free keys
free(cn[i].keys);
}
// Free array
free(cn);
}现在,我遇到了一个奇怪的问题,一个我创建的malloc数组。基本上,我尝试查找单元格的邻居,并使用以下两个方法->根据它们的值进行一些处理
struct cell * cellGetSuccessors(struct cell *c, struct cell *sstart, struct cell *sgoal, double km) {
int i;
// CREATE 5 CELLS
struct cell *cn = malloc(5 * sizeof (struct cell));
if (cn == NULL) {
printf("--> Unable to malloc *cn!\n");
errno = ENOMEM;
return NULL;
}
for(i = 0; i < 5; i++) {
cn[i].keys = malloc(sizeof(struct key));
if (cn[i].keys == NULL) {
printf("--> Unable to malloc *cn[%d].keys!\n", i);
errno = ENOMEM;
return NULL;
}
cellCopyValues(&cn[i], c);
}
// MAKE THEM NEIGHBORS
// PROCESS
return cn;
}
double cellRHS(struct cell *c, struct cell *sstart, struct cell *sgoal, double km, struct cell * prevCell) {
// GET NEIGHBORS of c
struct cell *cn = cellGetSuccessors(c, sstart, sgoal, km);
double minsum;
// SOME PROCESS TO UPDATE minsum
minsum = 5.232111; // SAY
// Free memory
cellFreeSors(cn);
return minsum;
}问题是,当我在cellRHS()中调用cellFreeSors()时,稍后会遇到问题。这就是这些函数的调用方式。
struct cell *u = cellCreateNew();
u->rhs = cellRHS(u, sstart, sgoal, km, prevCell);
queueAdd(&U, u);当我尝试打印队列->时,这会导致分段错误
QUEUE CONTENTS
==================================================================
F -> 0x2354550
L - >0x2354550
(1) [0x2354550] X 50.000000, Y 45.000000 PREV: (nil) NEXT: 0x4014000000000000
Segmentation fault正如您所看到的,下一个条目似乎由于某种原因被初始化了。在不使用cellRHS()的情况下执行相同的代码时,运行正常。->
struct cell *u = cellCreateNew();
queueAdd(&U, u);
QUEUE CONTENTS
==================================================================
F -> 0x2354550
L - >0x2354550
(1) [0x2354550] X 50.000000, Y 45.000000 PREV: (nil) NEXT: (nil)为什么cellFreeSors()会导致这个问题?我对cellRHS范围之外的u的派生邻居没有任何用处。我做错了什么?
谢谢..
**编辑queue_node的结构是
/* QUEUE NODE
* ----------------------------
* Contains a struct cell c and
* reference to next queue_node
*/
struct queue_node {
struct cell *c;
struct queue_node *next;
struct queue_node *prev;
};
/* PRIORITY QUEUE
* ----------------------------
* The queue itself, with first
* and last pointers to queue_nodes
*/
struct priority_queue {
struct queue_node *first;
struct queue_node *last;
};queuePrint()方法显示队列内容->
void queuePrint(struct priority_queue *q)
{
printf("\n\n\tQUEUE CONTENTS\n\t==================================================================\n");
int i = 1;
struct queue_node *temp = q->first;
printf("\tF -> %p\n\tL -> %p\n", q->first, q->last);
while(temp != NULL) {
printf("\t(%d) [%p]\tX %f, Y %f\tPREV: %p\tNEXT: %p", i, temp, temp->c->x, temp->c->y, temp->prev, temp->next);
printf("\n");
temp = temp->next;
i++;
}
printf("\n\n");
}发布于 2011-04-15 03:59:47
这里有一些建议:
https://stackoverflow.com/questions/5668768
复制相似问题