本文介绍了失败的malloc()的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

涉及失败的malloc()的单元测试代码路径的最佳方法是什么?在大多数情况下,这可能并不重要,因为您正在执行

What is the best way for unit testing code paths involving a failed malloc()? In most instances, it probably doesn't matter because you're doing something like

thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
  fprintf(stderr, "We're so screwed!\n");
  exit(EXIT_FAILURE);
}

,但是在某些情况下,您除了死亡之外还有其他选择,因为您已经为缓存或其他分配了一些额外的东西,并且可以回收该内存.

but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory.

但是,在那些您可以尝试从失败的malloc()中恢复的情况下,您在非常罕见的代码路径中执行了棘手且容易出错的事情,因此测试尤为重要.您实际上如何去做呢?

However, in those instances where you can try to recover from a failed malloc() that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this?

推荐答案

S.Paavolainen向我介绍了一个解决此问题的好方法.这个想法是通过自定义分配器来覆盖标准malloc(),您只需在链接器中执行此操作即可

I saw a cool solution to this problem which was presented to me by S. Paavolainen. The idea is to override the standard malloc(), which you can do just in the linker, by a custom allocator which

  1. 读取调用malloc()
  2. 的线程的当前执行堆栈
  3. 检查堆栈是否存在于存储在硬盘上的数据库中
  1. reads the current execution stack of the thread calling malloc()
  2. checks if the stack exists in a database that is stored on hard disk
  1. 如果堆栈不存在,则将堆栈添加到数据库中并返回NULL
  2. 如果堆栈确实已经存在,则正常分配内存并返回

然后,您只需多次运行单元测试:该系统会通过不同的控制路径自动枚举malloc()故障,并且比例如随机测试.

Then you just run your unit test many times: this system automatically enumerates through different control paths to malloc() failure and is much more efficient and reliable than e.g. random testing.

这篇关于失败的malloc()的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:42