Reputation: 5357
I have a simple question regarding mmap and munmap in Linux : is it possible that mmap
succeeds but munmap fails?
Assuming all the parameters are correctly given, for example, see the following code snippet. In what circumstances munmap failed!
will be printed??
char *addr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
... exit if mmap was not successful ...
... do some stuff using mmaped area ...
if( munmap(addr, 4096) == -1 ){
printf("munmap failed!\n");
}
Upvotes: 3
Views: 6966
Reputation: 5638
munmap
can fail with EINVAL
if it receives an invalid parameter.
It can also fail with ENOMEM
if the process's maximum number of mappings would have been exceeded. That can happen if you try to unmap a region in the middle of an existing map, and that results in two smaller maps.
You can see the maximum number of mappings per process with:
sysctl vm.max_map_count
You can increase it with, for example:
sysctl -w vm.max_map_count=131060
Be warned that if you don't check munmap
's return, you will not have any clue when that causes a crash or another kind of failure, specially in long-running processes where the error can linger.
An munmap EINVAL
, for instance, can point to a memory leak.
Also notice that mmap
fails with MAP_FAILED
, which is (void*)-1
and not NULL
.
Upvotes: 0
Reputation: 64283
Yes, it can fail. From mmunmap man pages :
Upon successful completion, munmap() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.
The error codes indicates that people do pass invalid parameters. But if you pass pointer you got from mmap(), and correct size, then it will not fail.
Assuming all the parameters are correctly given,
Then it will not fail. That is why most implementations (99%) just don't check the return value of unmmap(). In such case, even if it fails, you can't do anything (other then informing the user).
Upvotes: 1