|
List Info
Thread: Malloc behavior
|
|
| Malloc behavior |

|
2007-03-10 23:06:04 |
|
Hi,
I'm sorry for a so big email, but this might be a bug.
As some of you may know, there is a characteristic of malloc called overcommit, which lets a program "allocate" more virtual memory than is available on the system. I've set overcommit_memory=2 and turned off swap, but I believe the behaviour of malloc is not the expected.
Let me introduce the overcommit, then show the test code, then the results.
//-- Starting introduction of overcommit
According to http://www.die.net/doc/linux/man/man3/malloc.3.html
:
"By default, Linux follows an optimistic memory
allocation strategy. This means that when malloc() returns
non-NULL there is no guarantee that the memory really is available.
This is a really bad bug. In case it turns out that the system is
out of memory, one or more processes will be killed by the infamous
OOM killer. In case Linux is employed under circumstances where it
would be less desirable to suddenly lose some randomly picked
processes, and moreover the kernel version is sufficiently recent,
one can switch off this overcommitting behavior using a command
like
- # echo 2 > /proc/sys/vm/overcommit_memory
See also the
kernel Documentation directory, files
vm/overcommit-accounting and sysctl/vm.txt."
Looking at vm/overcommit-accounting:
"The Linux kernel supports the following overcommit handling modes
0 - Heuristic overcommit handling. Obvious overcommits of
address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to
allocate slightly more memory in this mode. This is the default.
1 - Always overcommit. Appropriate for some scientific applications.
2 - Don't overcommit. The total address space commit
for the system is not permitted to exceed swap + a configurable percentage (default is 50) of physical RAM. Depending on the percentage you use, in most situations
this means a process will not be killed while accessing pages but will receive errors on memory allocation as appropriate.
The overcommit policy is set via the sysctl `vm.overcommit_memory'.
The overcommit percentage is set via `vm.overcommit_ratio'."
//-- Ending introduction of overcommit
Then I started doing some tests. Below is my the test code:
//---------------------------- Top of test code
#include <stdio.h> #include <malloc.h> #include <limits.h> #include <string.h> #include <unistd.h>
int main(void) { int i; char *p; 4 char *r = malloc(1048576);
// Filling some useless space to copy later for (i = 0; i <= 1048576; i++) { *(char*)(r+i) = i; } for (i = 1; ; i++) { p = malloc(1048576);
if (p == NULL) { printf("malloc %d MB - %pn", i, p); printf("Returned nulln"); &nbs | |