使用 malloc 和 free 包装器
有人可以建议如何释放 main 以外的函数内分配的内存(例如:下面示例中的 mymalloc() )吗?从程序中的不同函数调用 free 是否有效?或者,既然我们在 myalloc() 中分配了内存,我们是否需要在 myalloc() 本身内部释放它? 请建议是否有更好的方法来实现以下内容。
int main(int argc, char ** argv) {
int * arr = {0};
foo();
return 1;
}
void mymalloc(int ** myarr1 ) {
(*myarr1) = (int*) malloc( sizeof(int)*25 );
(*myarr1)[3] = 69;
}
void myfree(int ** myarr2 ) {
if (*myarr2) {
memset(*myarr2, 0, sizeof(int)*25 );
free(*myarr2);
}
void foo() {
int * arr1 = {0};
mymalloc(&arr1);
printf("car[3]=%d\n",arr1[3]);
myfree (&arr1);
// Check if memory was freed
if (arr1) {
printf("ERROR: Memory allocated to arr1 is not freed.");
exit (1);
}
}
输出:
错误:分配给 arr1 的内存未释放。
Can somebody suggest how to free the memory allocated inside a function other than main (eg: mymalloc() in the below example)? Does calling free from a different function in the program work? Or, since we allocated memory in myalloc(), do we need to free it inside myalloc() itself?
Please suggest if there is a better way of implementing the below.
int main(int argc, char ** argv) {
int * arr = {0};
foo();
return 1;
}
void mymalloc(int ** myarr1 ) {
(*myarr1) = (int*) malloc( sizeof(int)*25 );
(*myarr1)[3] = 69;
}
void myfree(int ** myarr2 ) {
if (*myarr2) {
memset(*myarr2, 0, sizeof(int)*25 );
free(*myarr2);
}
void foo() {
int * arr1 = {0};
mymalloc(&arr1);
printf("car[3]=%d\n",arr1[3]);
myfree (&arr1);
// Check if memory was freed
if (arr1) {
printf("ERROR: Memory allocated to arr1 is not freed.");
exit (1);
}
}
Output:
ERROR: Memory allocated to arr1 is not freed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在程序中的任何位置
释放
使用malloc
创建的任何内容。使用
malloc
分配的内存来自内存的“堆”部分,并且将在程序的整个生命周期中持续存在,除非使用free
释放。You can
free
anything you have created withmalloc
anywhere in the program.Memory allocated with
malloc
comes from the "heap" section of memory, and will persist throughout the lifetime of a program unless released withfree
.没有必要在同一个函数中调用 malloc 和 free,但我对你的代码有一些评论:
It is not necessary to call malloc and free in the same function, but I have some remarks on your code:
您的内存已正确释放,但释放调用不会将指针设置为空,指针仍然指向现在无效的地址。如果您尝试在释放后向 arr1 写入内容,即使 arr1 没有指向 null,您也会遇到分段错误。
这就是为什么你应该在释放指针后立即将其设置为 null
your memory is correctly freed, but a free call does not set the pointer to null, the pointer is still pointing to the ,now invalid, address. If you where to try writing something to arr1 after the free, you would get a segmentation fault, even if arr1 is not pointing to null.
that's why you should always set a pointer to null just after freeing it