C:在错误的时间释放malloc数组?
|
我有一个
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
如您所见,该条目的NEXT似乎由于某种原因而被初始化。
在没有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()
引起此问题?除了u11 the的范围外,我对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\");
}
没有找到相关结果
已邀请:
1 个回复
旗低饶彤