【发布时间】:2023-03-27 07:30:01
【问题描述】:
int main(int argc, char **argv)
{
counter = 0;
int size = 5;
struct trie *mainTrie = malloc(size * sizeof(mainTrie));
test(mainTrie);
printf("%c", mainTrie[2].alphabet);
free(mainTrie->alphabet);
printf("%c", mainTrie[2].alphabet);
return 0;
}
测试函数只是为了看看我如何使用 malloc。我的实验是成功的,除了一件事:free(mainTrie)。
当我在“释放”内存空间后添加 printf("%c", mainTrie[2].alphabet) 时,输出仍然给了我存储在 mainTrie[2].alphabet 方法中的相同字母'测试'。
我是不是不明白什么?提前谢谢...
【问题讨论】:
-
您预计会发生什么,为什么?
-
struct trie *mainTrie = malloc(size * sizeof *mainTrie ); -
free()确实释放了分配的内存。您在释放内存后访问该内存的尝试具有未定义的行为。只是不要那样做。 -
@wildplasser:是的。同样值得解释的是,问题中的
malloc调用使用了错误的大小。它为 5 个指针分配空间,而不是为 5 个struct trie对象分配空间。malloc(size * sizeof(struct trie))也是正确的,但您的malloc(size * sizeof *mainTrie)等效且更强大。 -
还有stackoverflow.com/questions/20801582/… 和许多关于同一件事的许多其他问题。