Is it up to the programmer to deallocate on exit()

2020-02-14 08:28发布

I have a program and when I input wrong data from the keyboard it just exits with exit(1).

I was testing with Valgrind and while this happens there are no errors, but I can see that there are still reachable x bytes.

So my question: Is it up to the programmer to free memory before hitting an exit() or is the OS going to take care of it?

4条回答
萌系小妹纸
2楼-- · 2020-02-14 08:39

It's a good idea (and in old enough versions of Windows, it was essential), but when a program exit()s on modern operating systems its entire address space is reclaimed.

查看更多
Summer. ? 凉城
3楼-- · 2020-02-14 08:43

Assuming we are talking about user space, I think it is normally safe to assume that it is not an error to leave memory allocated on exit(). However, I consider bad design a program that reaches its end during normal execution and don't deallocate on exit.

查看更多
Deceive 欺骗
4楼-- · 2020-02-14 08:59

In the end, the OS will take care of it (on every modern OS, it was not the case with older version of Windows). Every ressource used by your program (memory, open file descriptors, ...) will be reclaimed by the OS when the program terminate (except some resource that are designed to survive process termination, mainly some sort of shared memory / mutex).

However, valgrind is here to help you track memory leak and will report every available memory region so that you can, if you want, manually release them.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-14 09:00

It is a bad idea to free memory before exit()ing. It wastes time for no good reason, and in multithreaded programs it can actually cause bugs if other threads are not joined first and may access some of the allocated memory.

The "still reachable" is not a leak. Consider:

#include <stdlib.h>
void *a_global;
int main() {
  void *a_local = malloc(10);
  a_global = malloc(20);
}

gcc -g t.c && valgrind ./a.out

==12228== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==12228== Using Valgrind-3.7.0.SVN and LibVEX; rerun with -h for copyright info
==12228== Command: ./a.out
==12228== 
==12228== 
==12228== HEAP SUMMARY:
==12228==     in use at exit: 30 bytes in 2 blocks
==12228==   total heap usage: 2 allocs, 0 frees, 30 bytes allocated
==12228== 
==12228== LEAK SUMMARY:
==12228==    definitely lost: 10 bytes in 1 blocks
==12228==    indirectly lost: 0 bytes in 0 blocks
==12228==      possibly lost: 0 bytes in 0 blocks
==12228==    still reachable: 20 bytes in 1 blocks
==12228==         suppressed: 0 bytes in 0 blocks

Here, by the time you've reached exit, a_local has gone out of scope. There is no way to free that memory; it is lost forever. That's a leak.

OTOH, you could easily free a_global (you just shouldn't), it's reachable, and is not a leak.

查看更多
登录 后发表回答