无法在 Objective-C iPhone 开发中释放链表
我正在为 iPhone 编写一个应用程序,它使用链接列表来跟踪一组点。我在其他 C 程序中一次又一次成功地使用了链表,但我从未在 iPhone 上使用过链表,而且我的“freeList”函数崩溃了。
pointNode * temp;
pointTrain = lPoints->next;
while (pointTrain) {
temp = pointTrain->next;
free(pointTrain);
pointTrain = temp;
}
这就是我释放列表的方式,“lPoints”是头部,并且始终在运行时分配。该代码在添加更多节点之前执行,但即使“pointTrain”为 NULL,它似乎仍然会执行,这应该使其跳过 while 循环。不幸的是,循环仍在执行,并且程序在 free(pointTrain) 上崩溃了,
有什么我没有看到的吗?
在循环中像这样添加点:
pointTrain->x = onPx / trueWidth;
pointTrain->y = onPx % trueWidth;
pointTrain->next = (pointNode*)malloc(sizeof(pointNode));
pointTrain = pointTrain->next;
I'm writing an application for iPhone, that uses a linked list to keep track of a set of points. I've used linked lists time and time again successfully in other C programs, but I've never used a linked list on iPhone, and my 'freeList' function is crashing.
pointNode * temp;
pointTrain = lPoints->next;
while (pointTrain) {
temp = pointTrain->next;
free(pointTrain);
pointTrain = temp;
}
This is how I'm freeing my list, 'lPoints' is the head, and is always allocated during runtime. This code is executed before any more nodes are added, but it seems to still execute even though "pointTrain" is NULL, which SHOULD make it skip the while loop. Unfortunately, the loop is still executed, and the program crashes on free(pointTrain)
Is there something I'm just not seeing?
Points are added like so within a loop:
pointTrain->x = onPx / trueWidth;
pointTrain->y = onPx % trueWidth;
pointTrain->next = (pointNode*)malloc(sizeof(pointNode));
pointTrain = pointTrain->next;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一位智者曾经说过:“我宁愿骑马顺着它前进的方向。”
当您可以使用一个完美的
NSMutableArray
类时,不要滚动您自己的结构。数组的线性迭代既便宜又简单,并且该类带有自己的内存管理挂钩,您所要做的就是使用它们。我在转向 Objective-C 的 C 和 C++ 开发人员中经常看到这种情况。我的下一个项目是取消一个非常高级的 C++ 人员在过去六个月里完成的项目。看看代码,很明显他几乎把所有时间都花在了与框架争论上。此时他实际上已经构建了自己的框架。
A wise man once said, "I'd rather ride a horse the direction it's going."
Don't roll your own struct when there's a perfectly good
NSMutableArray
class you could be using. Linear iteration of an array is cheap and easy, and the class comes with its own memory management hooks, and all you have to do is USE them.This is something I see a lot with C and C++ devs who pop over to Objective-C. The next project on my plate is to un-fubar a project that a VERY senior C++ guy spent the last six months on. Looking at the code, it's plain that he spent almost all of that time arguing with the framework. He's practically built his own framework at this point.
您是否显式初始化
NULL
或nil
旁边?如果不是,它可能已经被设置为某个非零值,因此 while (pointTrain) 仍将计算为 true。
Are you explicitly initializing next to
NULL
ornil
?If not, its likely to already be set to some non zero value, and therefore
while (pointTrain)
will still evaluate to true.