use*_*739 5 c memory malloc ulimit
我想malloc()通过限制可用内存来失败。
$ ulimit -v 1000
$ ./main.exe 10000000
0x102bfb000
Run Code Online (Sandbox Code Playgroud)
但即使使用 ulimit,以下程序仍能正确完成。有人知道如何malloc()失败吗?谢谢。
#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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:以上是在 Mac OS X 上。
在 Linux 上,我遇到了分段错误。为什么malloc()会导致segmentation fault?如何使malloc()返回空指针?
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |