涉及失败的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()故障,并且比例如随机测试.
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()的单元测试
发布评论