malloc does not return null when out of memory
Chuck Swiger
cswiger at mac.com
Thu Jul 24 08:15:48 PDT 2003
Kris Kennaway wrote:
> On Wed, Jul 23, 2003 at 11:44:11PM -0400, Mike Tancsa wrote:
[ ... ]
>>> Ah, the annual "memory overcommit" thread. I thought we were overdue
>>> for one.
>>
>> But why does the man page for malloc (3) say,
>>
>> If malloc() fails, a NULL pointer is returned.
>
> Words fail me.
Don't worry about it; you've still got sarcasm to fall back on. :-)
I don't think the following is a particularly good idea, as the existing prezero
('Z') or junk ('J') options will also serve to reference memory and prevent
the "memory overcommit issue", but:
22-sec# diff -du malloc.c_old malloc.c
--- malloc.c_old Thu Jul 24 10:36:43 2003
+++ malloc.c Thu Jul 24 10:49:41 2003
@@ -229,6 +229,9 @@
/* junk fill ? */
static int malloc_junk;
+/* write a single byte per page to disable overcommit behavior */
+static int malloc_overcommit;
+
#ifdef HAS_UTRACE
/* utrace ? */
@@ -418,6 +421,8 @@
case 'R': malloc_realloc = 1; break;
case 'j': malloc_junk = 0; break;
case 'J': malloc_junk = 1; break;
+ case 'o': malloc_overcommit = 0; break
+ case 'O': malloc_overcommit = 1; break
#ifdef HAS_UTRACE
case 'u': malloc_utrace = 0; break;
case 'U': malloc_utrace = 1; break;
@@ -705,6 +710,7 @@
imalloc(size_t size)
{
void *result;
+ int stride;
if (suicide)
abort();
@@ -716,8 +722,13 @@
else
result = malloc_pages(size);
- if (malloc_zero && result)
- memset(result, 0, size);
+ if (result) {
+ if (malloc_zero)
+ memset(result, 0, size);
+ else if (malloc_overcommit)
+ for (stride = 0; stride <= size; stride += malloc_pagesize)
+ ((char *)result)[stride] = SOME_JUNK;
+ }
return result;
}
--
-Chuck
More information about the freebsd-stable
mailing list