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);
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)
.
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.
Thanks.