本文介绍了确实在_SUCCESS和_FAILURE上都存在exit()释放的已分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一段简短的代码,如果失败,将两次调用exit(3).这些调用会释放由malloc分配的内存吗? Google搜索曾经说过,甚至很多时候都没有……

This a short snippet of code, with two calls to exit(3) in case of failure.Do these calls deallocate memory allocated by malloc? Google search once says it does, and even more times, it doesn't...

我应该添加free()吗?

Should I add free()?

也:if (!word)更好(它也适用于例如word == 0,它与word == NULL不同,所以我想这是错误的)或if (word == NULL)吗?

Also: which is better if (!word)(it would also work for eg. word == 0 which is different from word == NULL, so I guess it is wrong) or if (word == NULL) ?

char *word = NULL, *temp = NULL;
    word = (char *)malloc(sizeof(char) * size);

    if (!word) {            /* or maybe rather it should be (word == NULL)  */
        perror("malloc fail");
        if (fclose(fp)) {
            perror("fclose fail");
            exit(3);                            /* exit without free ? */
        }
        exit(3);                                /* exit without free ? */
    }

提前谢谢!

推荐答案

是的,将返回所有内存.顺便说一句,退出后,您要如何处理剩余的内存?
还是您担心exit()中的内存泄漏?如果不回收内存,则每个退出进程都会泄漏更多内存,这是可信的操作系统所无法承受的.因此,除了有故障的操作系统外,不要再担心内存问题,并在需要的地方使用exit().

Yes, all memory is returned. BTW, what would you want to do with leftover memory after the exit anyway?
Or are you worrying about a memory leak in exit()? If the memory weren't reclaimed, it would leak a bit more with each exiting process, which is something no credible OS could afford. So, except for a buggy OS, stop worrying about memory and use exit() wherever you need it.

要回答代码注释中的问题(是否免费),我想说的是适当的软件工程,以便为每个malloc编写一个相应的free.如果这看起来很难,则表明您的代码存在结构性问题.在退出之前释放所有内存的好处是,您可以使用强大的工具,例如valgrind来检查其余代码中的内存泄漏,而不会向您展示给我们的malloc误报.

To answer the questions in the comments of your code, whether to free, I'd say it's proper software engineering to write a corresponding free with every malloc. If that appears hard, it is pointing to a structural problem in your code. The benefit of freeing all memory before exiting is that you can use powerful tools like valgrind to check for memory leaks in the rest of your code without false positives from the malloc you've shown us.

请注意,在失败失败之后,尝试释放结果毫无意义-无论如何它都是空指针.

Note that after a failed malloc there is no point in attempting to free the result--it's a null pointer anyway.

第三,相对于if (!pointer),我更喜欢if (pointer == NULL),但这完全是主观的,我可以阅读和理解这两者:-)

And third, I prefer if (pointer == NULL) over if (!pointer) but this is totally subjective and I can read and understand both :-)

这篇关于确实在_SUCCESS和_FAILURE上都存在exit()释放的已分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:45