失败的malloc()的单元测试

编程入门 行业动态 更新时间:2024-10-11 05:29:47
本文介绍了失败的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

  • 读取调用malloc()
  • 的线程的当前执行堆栈
  • 检查堆栈是否存在于存储在硬盘上的数据库中
  • reads the current execution stack of the thread calling malloc()
  • checks if the stack exists in a database that is stored on hard disk
  • 如果堆栈不存在,则将堆栈添加到数据库中并返回NULL
  • 如果堆栈确实已经存在,则正常分配内存并返回
  • 然后,您只需多次运行单元测试:该系统会通过不同的控制路径自动枚举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()的单元测试

    本文发布于:2023-10-10 21:56:28,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1479866.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:单元测试   malloc

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!