【发布时间】:2012-06-19 17:37:57
【问题描述】:
我正在尝试学习 C,目前正在尝试编写一个基本的堆栈数据结构,但我似乎无法掌握基本的 malloc/free 正确。
这是我一直在使用的代码(我只是在这里发布一小部分来说明一个特定的问题,而不是全部代码,但错误消息是通过在valgrind中运行此示例代码生成的)
#include <stdio.h>
#include <stdlib.h>
typedef struct Entry {
struct Entry *previous;
int value;
} Entry;
void destroyEntry(Entry entry);
int main(int argc, char *argv[])
{
Entry* apple;
apple = malloc(sizeof(Entry));
destroyEntry(*(apple));
return 0;
}
void destroyEntry(Entry entry)
{
Entry *entry_ptr = &entry;
free(entry_ptr);
return;
}
当我通过valgrind 和--leak-check=full --track-origins=yes 运行它时,我收到以下错误:
==20674== Invalid free() / delete / delete[] / realloc()
==20674== at 0x4028E58: free (vg_replace_malloc.c:427)
==20674== by 0x80485B2: destroyEntry (testing.c:53)
==20674== by 0x8048477: main (testing.c:26)
==20674== Address 0xbecc0070 is on thread 1's stack
我认为这个错误意味着destroyEntry函数不允许修改在main中显式分配的内存。那正确吗?为什么我不能在另一个函数中只 free 我在 main 中分配的内存? (这种行为是否特定于 main?)
【问题讨论】:
-
+1 表示明确的问题和 SSCCE。
-
@MatteoItalia 我以前从未听说过SSCCE。绝对是个好概念。感谢您向我介绍它。
标签: c pointers memory-management malloc free