Add a test case for OOM while allocating memory

This commit is contained in:
Andreas Pasiopoulos 2016-08-11 17:18:46 +03:00
parent 8f067962f6
commit 835290dfdf

View File

@ -5,8 +5,9 @@
static int malloc_called = 0;
static int free_called = 0;
static size_t malloc_used = 0;
/* helper */
/* helpers */
static void create_and_free_complex_object()
{
json_t *obj;
@ -22,6 +23,20 @@ static void create_and_free_complex_object()
json_decref(obj);
}
static void create_and_free_object_with_oom()
{
json_t *obj = json_object();
for (int i = 0; i < 10; i++)
{
char key[4];
snprintf(key, sizeof key, "%d", i);
json_object_set_new(obj, key, json_integer(i));
}
json_decref(obj);
}
static void *my_malloc(size_t size)
{
malloc_called = 1;
@ -49,6 +64,32 @@ static void test_simple()
}
static void *oom_malloc(size_t size)
{
if (malloc_used + size > 800)
return NULL;
malloc_used += size;
return malloc(size);
}
static void oom_free(void *ptr)
{
free_called++;
free(ptr);
}
static void test_oom()
{
free_called = 0;
json_set_alloc_funcs(oom_malloc, oom_free);
create_and_free_object_with_oom();
if (free_called == 0)
fail("Allocation with OOM failed");
}
/*
Test the secure memory functions code given in the API reference
documentation, but by using plain memset instead of
@ -84,4 +125,5 @@ static void run_tests()
{
test_simple();
test_secure_funcs();
test_oom();
}