如何限制可用内存以使`malloc()`失败? [英] How to limit available memory to make `malloc()` fail?

查看:64
本文介绍了如何限制可用内存以使`malloc()`失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过限制可用内存来使 malloc()失败.

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

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

但是即使使用ulimit,以下程序仍然可以正确完成.有人知道如何使 malloc()失败吗?谢谢.

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;
}

上面是在Mac OS X上.

The above is on Mac OS X.

在Linux上,我遇到了分段错误.为什么 malloc()会导致分段错误?如何使 malloc()返回NULL指针?

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

推荐答案

基于文档:如果ptr是空指针,则该函数的行为类似于malloc ,分配一个新的大小为字节的块,并返回一个指向其开头的指针

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

这篇关于如何限制可用内存以使`malloc()`失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆