Proper way to test code with calls to malloc()

17 views
Skip to first unread message

MrMOSFET

unread,
Oct 6, 2022, 9:42:49 AM10/6/22
to cpputest
Hi all,

Let's assume I have a C file, with a very simple function:

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "code.h"

char *return_str_dup(const char *str)
{
    size_t len = strlen(str);
    char *dup = malloc(len + 1);
    if (dup == NULL) {
        return NULL;
    }
    strncpy(dup, str, len + 1);
    return dup;
}


And I want to write a unit test that checks to make sure the function return NULL if malloc fails (doesn't crash with NULL pointer access).  Is this possible with CppUTest?  I have tried following along with TestMemoryAllocatorTest.cpp without much luck. 

Basically it looks like this:

TEST(tests, test_dup_malloc_fails)
{
    failableMallocAllocator->failAllocNumber(1);
    void *mem = return_str_dup("Why, hello there!");
    POINTERS_EQUAL(NULLPTR, mem);
};

But I can't get malloc to return NULL. 

Any help would be appreciated.  Thanks!

Bas Vodde

unread,
Oct 8, 2022, 3:12:34 PM10/8/22
to cppu...@googlegroups.com

Hi Mr Mosfet,

In order for the malloc checking to work, you’ll need to ensude the malloc is replace with “cpputest_malloc”

This is usually done by appending a include file that does a #define and declares the cpputest_malloc.

Without that, the mallow call will still like to the stdC malloc and there is no easy way to hijack that.

Thanks,

Bas

--
You received this message because you are subscribed to the Google Groups "cpputest" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cpputest+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cpputest/c0584abe-196b-4e8d-b464-acca522a1199n%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages