测试内存分配失败的正确行为

时间:2016-11-08 14:58:24

标签: c++ c linux testing dynamic-memory-allocation

我们为Linux服务器提供了相对较大的代码库,它是使用dlopen()在启动期间加载的动态链接库和服务器模块。服务器以及大多数其他组件都是用C ++ 11编写的,但有些是在C99中。

可以使用哪些方法来测试服务器,其依赖项和模块是否正确处理内存分配失败,例如malloc / calloc返回NULL,运算符newnew[]投掷std::bad_alloc等,包括来自std::string::resize()的分配失败等等?

过去,我尝试使用memory allocation hooks将内存分配失败注入C应用程序,但我认为这些不适用于C ++。我应该考虑哪些其他选择或方法?

2 个答案:

答案 0 :(得分:1)

事实上,挂入C malloc已经足够了,因为在引擎盖下,运行new的gcc C ++默认实现确实调用了malloc,你确认你只需要一个gcc兼容的解决方案。

我可以用这个简单的程序演示它:

mem.c ++:

#include <iostream>
#include <string>

class A {
    int ival;
    std::string str;

public:
    A(int i, std::string s): ival(i), str(s) {}
    A(): ival(0), str("") {};

    int getIval() const {
        return ival;
    }
    std::string getStr() const {
        return str;
    }
};

int main() {
    A a(2, "foo");

    std::cout << &a << " : " << a.getIval() << " - " << a.getStr() << std::endl;

    return 0;
}

memhook.c:

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

extern void *__libc_malloc(size_t size);

void* malloc (size_t size) {
    fprintf(stderr, "Allocating %u\n", size);
    return NULL;
//    return __libc_malloc(size);
}

当返回NULL(如上所述)时,程序显示:

Allocating 16
Allocating 100
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Abandon (core dumped)

这证明从声明的malloc函数返回NULL会导致C ++代码中出现std::bad_alloc异常

取消注释return __libc_malloc(size);分配由libc malloc完成并且输出变为:

Allocating 16
0xbfe8d2e8 : 2 - foo

答案 1 :(得分:-1)

在Linux上,您可以挂钩操作系统以强制分配失败

man 2 mlockall

mlockall(MCL_CURRENT|MCL_FUTURE);

应该做你想做的事。