c - 使 malloc 自动失败以测试 malloc 失败时的情况

标签 c pointers memory memory-management

我一直在为我创建的一个简单程序创建测试。我总是使用类似这样的方法检查使用 malloc 分配内存是否失败

int* ptr = malloc(sizeof(int) * x);

if(!ptr){
    //...
    exit(1); // but it could also not terminate abnormally and do something else
}

但通常,至少对于我的程序,malloc 永远不会失败,而那些我无法真正确定性地测试 malloc 失败的情况。

我的问题是:如果我无法控制 malloc 是否会失败,我该如何测试程序是否会出现内存分配失败?当 malloc 失败时,我应该怎么做才能进行确定性测试?

最佳答案

当我需要在不同阶段测试内存分配失败时,我使用了这样的函数 xmalloc():

static int fail_after = 0;
static int num_allocs = 0;

static void *xmalloc(size_t size)
{
    if (fail_after > 0 && num_allocs++ >= fail_after)
    {
        fputs("Out of memory\n", stderr);
        return 0;
    }
    return malloc(size);
}

测试工具(同一源文件的一部分)可以将 fail_after 设置为任何合适的值,并在每次新测试运行之前将 num_allocs 重置为零。
int main(void)
{
    int no1 = 5;

    for (fail_after = 0; fail_after < 33; fail_after++)
    {
        printf("Fail after: %d\n", fail_after);
        num_allocs = 0;
        test_allocation(no1);
    }

    printf("PID %d - waiting for some data to exit:", (int)getpid());
    fflush(0);
    getchar();

    return 0;
}

然后你可以安排调用 xmalloc() 来代替“真实的” malloc() :
#define malloc(x)    xmalloc(x)

这将放在 xmalloc() 的定义之后——尽管如果需要的话,有办法解决这个问题。您可以通过各种方式进行调整:也限制总大小,安排每第 N 次分配失败,安排在 M 次成功分配后连续分配 N 次失败,等等。

关于c - 使 malloc 自动失败以测试 malloc 失败时的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38023749/

相关文章:

c - 扩展 ASCII 字符在 int 10h 中不起作用

c - Malloc 在递归函数中崩溃

c - 返回数组 C 的指针时出现指针段错误

Java - 处理内存中的文件而不需要磁盘R/W

c - 警告 : passing argument 1 of 'quicksort' makes pointer from integer without a cast

c - 如何在 ubuntu 上编译内核 3.14(从 kernel.org 下载)

具有不同类型作为参数的 C++ 条件运算符

c++ - 将对非指针成员变量的引用作为指针返回可以吗?

python - python 对象列表,每个对象都有自己的数组字典。附加到一个附加到所有

c++ - 什么时候使用虚拟内存(windows)?