user1424739
user1424739

Reputation: 13785

How to limit available memory to make `malloc()` fail?

I'd like to make malloc() fail by limiting the memory available.

$ ulimit -v 1000
$ ./main.exe 10000000
0x102bfb000

But even with ulimit, the following program still finishes correctly. Does anybody know how to make malloc() fail? Thanks.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    size_t size = atoi(argv[1]);
    void *ptr = NULL;

    if((ptr = malloc(size)) == NULL) {
        perror("malloc()");
        exit(1);
    }

    printf("%p\n", ptr);
    free(ptr);
    return 0;
}

EDIT: The above is on Mac OS X.

On Linux, I got segmentation fault. Why malloc() can cause segmentation fault? How to make malloc() return a NULL pointer?

Upvotes: 4

Views: 1714

Answers (2)

Joachim
Joachim

Reputation: 991

The memory limit of 1MB is not big enough to reach the actual malloc call. On my linux system alone libc is 2MB. So 1MB is not enough memory to completely load the application and even reach the main function.

For me, using ulimit -v 5000 is sufficient to print the malloc(): Cannot allocate memory message.

Upvotes: 2

Michał Marszałek
Michał Marszałek

Reputation: 160

Based on documentation: In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning

If you want to limit memory that program can allocate you can use:

#include <sys/time.h>
#include <sys/resource.h>
rlimit l;
getrlimit(RLIMIT_AS, &l);
l.rlim_cur = 1000;
setrlimit(RLIMIT_AS, &l);

http://man7.org/linux/man-pages/man2/setrlimit.2.html

Upvotes: 1

Related Questions