我正在学习 C 的基础知识,现在正在使用 malloc()。假设我有一个函数,它要求用户输入,用所述数据填充一个结构,并将该结构保存在一个数组中(全部通过主函数的引用传递)。
我通过 Valgrind 运行程序,我得到了“仍然可以访问”的字节(应该没问题吧?不认为是泄漏),但是保存的任何数据都会丢失块。
程序完成运行后,我将如何释放该内存?此外,我在代码中有一些 (2) 问题只是为了澄清一些事情,如果有人可以向我解释,我将不胜感激。
这是一些类似于我正在尝试做的代码:
我声明了以下结构:
struct Person {
char name[MAX_INPUT];
int age;
};
我正在编写一个这样的函数:
int function2(struct Person *list, int *index) {
struct Person *prsn = malloc(sizeof(struct Person));
// !Why do we sometimes cast the malloc or not?
// I sometimes get errors when I do, sometimes when I don't,
// while the surrounding code is pretty much the same.
assert(prsn != NULL);
// User input code goes here ...
// Now to save the Person created
strcpy(prsn->name, nameInput);
prsn->age = ageInput;
list[(*index)++] = *prsn;
// !Why use the dereferencing *prsn here?
// why not directly prsn? Or is that saving the memory address and not very useful.
return 0;
}
这是我的主要功能:
int main(int argc, char *argv[]) {
struct Person personList[MAX_SIZE];
int index;
function2(personList, &index);
// Before closing, I want to free any mallocs I have done here. free()
return 0;
}
Valgrind 报告:
LEAK SUMMARY:
==1766== definitely lost: 44 bytes in 1 blocks
==1766== indirectly lost: 0 bytes in 0 blocks
==1766== possibly lost: 0 bytes in 0 blocks
==1766== still reachable: 10,355 bytes in 34 blocks
==1766== suppressed: 0 bytes in 0 blocks
先感谢您。
编辑:修复了function2参数,返回和其他东西。我很抱歉,写它是为了说明我关于释放内存的主要问题。感谢您的更正提示,但真正的代码实际上是正确编译的。
Edit2:在建议使用 free() 的 main 末尾添加一个简单循环后,我收到以下错误。
==2216== LEAK SUMMARY:
==2216== definitely lost: 44 bytes in 1 blocks
==2216== indirectly lost: 0 bytes in 0 blocks
==2216== possibly lost: 0 bytes in 0 blocks
==2216== still reachable: 10,355 bytes in 34 blocks
==2216== suppressed: 0 bytes in 0 blocks
==2216==
==2216== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==2216==
==2216== 1 errors in context 1 of 2:
==2216== Invalid free() / delete / delete[] / realloc()
==2216== at 0x563A: free (in /usr/local/Cellar/valgrind/3.8.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==2216== by 0x10000194E: main (in ./test.out)
==2216== Address 0x7fff5fbf9dd0 is on thread 1's stack
==2216==
==2216== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)