单元测试C库,内存管理 [英] Unit testing C library, memory management

查看:66
本文介绍了单元测试C库,内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个很大的C库,该库现在没有任何测试.随着API的最终确定,我想开始编写单元测试.

I am working on a quite large C library that doesn't have any tests now. As the API starts to be final, I'd like to start writing unit tests.

几乎所有我的函数都作用在第一个参数(一个结构)上.

Nearly all my functions acts on the first parameter (a structure).

单元测试的幼稚方法是使前函数调用结构处于已知状态,调用该函数,然后将前调用结构与预期结果进行比较.

The naive approach to unit test is to have the pre function call structure in a known state, call the function, and then compare the pre call structure with the expected result.

现在这可以处理由标量类型组成的结构,但是对于分配的内存,我想知道您使用的是哪种方法.

Now this works with structure composed of scalar types, but as for allocated memory, I was wondering what kind of approach you were using.

例如,想象一下当您执行以下操作时的图像结构:

For example, imagine an image structure, when you do:

CreateImage(&img, x, y);

您希望img-> x是x,img-> y是y,img-> pixels是指向足以容纳x * y * sizeof(pixel)的对象的指针.

you expect the img->x to be x, img->y to be y and img->pixels to be a pointer to something big enough to hold x * y * sizeof(pixel).

检查前两个是微不足道的,但是img-> pixels呢?我并不是要检查malloc调用是否成功,因为我可以过载 malloc,但我想知道是否正确调用了malloc.

Checking for the first two is trivial, but what about the img->pixels? I don't mean to check if the malloc call was successful, as I can overload malloc, but I want to know if malloc was called properly.

在这样的情况下,这尤其重要:

This is especially important in case like that:

CreateImage(*img, x, y)
{
    img->x = x; img->y = y;
    /* do something, dhoo, that something is broken and modify x or y */
    img->pixels = malloc(x * y * sizeof(pixel)); /* wrong allocation size */
    if(!img->pixels) error("no memory");
}

我希望我的问题很清楚.

I hope my question is clear.

谢谢.

推荐答案

在单元测试中,让重载的malloc函数记录调用它的值(例如alloc_size).

In your unit test, have your overloaded malloc function log the value that it was called with (eg. alloc_size).

然后只需测试所有这些都是正确的:

Then just test that all of these are true:

  • alloc_size % sizeof(pixel) == 0
  • alloc_size % x == 0
  • alloc_size % y == 0
  • ((alloc_size / sizeof(pixel)) / x ) / y == 1
  • alloc_size % sizeof(pixel) == 0
  • alloc_size % x == 0
  • alloc_size % y == 0
  • ((alloc_size / sizeof(pixel)) / x ) / y == 1

不要只是从您正在测试的函数中复制代码-即.乘法-因为您可能最终会复制错误.

Do not just replicate the code from the function you're testing - ie. the multiplication - because you may end up replicating a bug.

在这种情况下,您可能可能会复制一个错误-如果在xy上没有边界测试,那么malloc调用中的乘法本身就是错误的(考虑一下会发生什么)发生在具有32位size_tsizeof(pixel) == 4x == 40000y == 40000的系统上).

In this case you would potentially replicate a bug - if there's no bounds tests on x and y, then the multiplication in the malloc call is itself buggy (consider what would happen on a system with a 32 bit size_t, sizeof(pixel) == 4, x == 40000 and y == 40000).

这篇关于单元测试C库,内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆