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?