iPhone ansi c : pointer being freed was not allocated

标签 iphone c pointers memory structure

我在我的 iPhone 应用程序中使用 c lib。 c lib 是由我无权访问的人编写的。

但是我收到错误,对象 0xa6000d 正在被释放但未分配。调试变量屏幕截图在这里。

enter image description here

struct GtsMsg 定义为,

struct msg {
    int offset;
    int dataLength;
    u8* data;
    cBool expandable;
    cBool owned;
    u8* mid2key;
};

#define GtsMsg struct msg


void freeMessageData(GtsMsg* msg) {
    if (msg == NULL) return;
    if (msg->owned) {
        if (msg->data != NULL) {
            free(msg->data);
        }
    }
    free(msg->mid2key);
    memset(msg, 0, sizeof(GtsMsg));
}

malloc_error_break 的断点是 free(msg->data) 行。

我添加了检查 if (msg->data != NULL),但它不起作用。有什么方法可以检查msg->data或msg的内存是否分配?

您认为 *data = (u8)'\0' 处有什么可疑之处吗?

提前致谢!

最佳答案

感谢大家的建议。 感谢 hmjd 的提示。

我发现该结构体在 cpp 类中使用,该类的析构函数调用 freeMessageData。但我找不到该结构已初始化。因此,如果我在声明中将结构初始化为 NULL,则可以避免空闲内存问题并且不会崩溃。

这是 simonc 建议的东西。如果他写下这个作为答案而不是评论,我可以接受。

摘自hmjd的评论,

The check for NULL is useless as free() will be a no-op if the pointer passed to it is NULL. Just because a pointer is not NULL does not mean it points a valid memory location (the memory may have already been freed or the pointer was never initialized to NULL). It is the responsibility of the programmer to ensure that the pointer is valid before attempting to free it.

关于iPhone ansi c : pointer being freed was not allocated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893872/

相关文章:

pointers - 声明 const 指针为 int 吗?

C 指针参数不匹配编译警告

iphone - 在 uitextfield 中显示笑脸图标

iphone - 翻转由 UINavigationController 管理的 UIViewController 会隐藏导航栏

iphone - 写入 UITextView

iphone - 无法显示 UIWebView 以显示带有自定义 URL 的 SFUZipEndOfCentralDirectoryError 错误的 docx/xlsx 文件

有人可以向我解释如何浏览这段代码吗?

c: fopen 和 fprint

c - ISR 中的事件通知

c - 在 C 中取消引用指向不完整类型(具有明确定义的结构)的指针