在不同的功能分配的内存? [英] Free memory allocated in a different function?
问题描述
我想学习C和我目前正在写一个基本的堆栈数据结构,但我似乎无法得到基本的malloc
/ 免费
的权利。
I'm trying to learn C and I'm currently trying to write a basic stack data structure, but I can't seem to get basic malloc
/free
right.
这里的code我一直在使用(我只是张贴的一小部分在这里说明一个具体的问题,而不是总code,但通过运行这个例子只是$产生的错误信息C $℃的的valgrind
)
Here's the code I've been using (I'm just posting a small part here to illustrate a specific problem, not the total code, but the error message was generated just by running this example code in 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
- 泄漏检查=全--track-起源= YES
When I run it through valgrind
with --leak-check=full --track-origins=yes
, I get the following error:
==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
功能是不允许修改主要明确分配的内存。是对的吗?为什么我不能只是免费
我在主
在另一个函数分配的内存? (并且这种行为在某种程度上具体到主?)
I think this error means that the destroyEntry
function is not allowed to modify memory allocated explicitly in main. Is that right? Why can't I just free
the memory I allocated in main
in another function? (and is this behavior somehow specific to main?)
推荐答案
当你传递参数给一个函数,它复制了一份,而且功能适用于该副本。所以你的情况,你想免费
原来的对象,这没有任何意义的副本。
Whenever you pass a parameter to a function, a copy is made, and the function works on that copy. So in your case, you are trying to free
a copy of the original object, which doesn't make any sense.
您应该修改你的函数取一个指针,然后你可以把它称之为免费
直接在该指针。
You should modify your function to take a pointer, and then you can have it call free
directly on that pointer.
这篇关于在不同的功能分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!