22
33#include <setjmp.h>
44#include <signal.h>
5+ #include <stdint.h>
56#include <stdio.h>
67#include <stdlib.h>
78#include <string.h>
@@ -58,6 +59,12 @@ static jmp_buf env;
5859static volatile sig_atomic_t jmp_ready = false;
5960static bool time_limited = false;
6061
62+ /* For test_malloc and test_calloc */
63+ typedef enum {
64+ TEST_MALLOC ,
65+ TEST_CALLOC ,
66+ } alloc_t ;
67+
6168/* Internal functions */
6269
6370/* Should this allocation fail? */
@@ -115,17 +122,23 @@ static size_t *find_footer(block_element_t *b)
115122 return p ;
116123}
117124
118- /* Implementation of application functions */
119-
120- void * test_malloc (size_t size )
125+ static void * alloc (alloc_t alloc_type , size_t size )
121126{
122127 if (noallocate_mode ) {
123- report_event (MSG_FATAL , "Calls to malloc disallowed" );
128+ char * msg_alloc_forbidden [] = {
129+ "Calls to malloc are disallowed" ,
130+ "Calls to calloc are disallowed" ,
131+ };
132+ report_event (MSG_FATAL , "%s" , msg_alloc_forbidden [alloc_type ]);
124133 return NULL ;
125134 }
126135
127136 if (fail_allocation ()) {
128- report_event (MSG_WARN , "Malloc returning NULL" );
137+ char * msg_alloc_failure [] = {
138+ "Malloc returning NULL" ,
139+ "Calloc returning NULL" ,
140+ };
141+ report_event (MSG_WARN , "%s" , msg_alloc_failure [alloc_type ]);
129142 return NULL ;
130143 }
131144
@@ -142,7 +155,7 @@ void *test_malloc(size_t size)
142155 new_block -> payload_size = size ;
143156 * find_footer (new_block ) = MAGICFOOTER ;
144157 void * p = (void * ) & new_block -> payload ;
145- memset (p , FILLCHAR , size );
158+ memset (p , ! alloc_type * FILLCHAR , size );
146159 // cppcheck-suppress nullPointerRedundantCheck
147160 new_block -> next = allocated ;
148161 // cppcheck-suppress nullPointerRedundantCheck
@@ -156,16 +169,22 @@ void *test_malloc(size_t size)
156169 return p ;
157170}
158171
172+ /* Implementation of application functions */
173+
174+ void * test_malloc (size_t size )
175+ {
176+ return alloc (TEST_MALLOC , size );
177+ }
178+
159179// cppcheck-suppress unusedFunction
160180void * test_calloc (size_t nelem , size_t elsize )
161181{
162182 /* Reference: Malloc tutorial
163183 * https://danluu.com/malloc-tutorial/
164184 */
165- size_t size = nelem * elsize ; // TODO: check for overflow
166- void * ptr = test_malloc (size );
167- memset (ptr , 0 , size );
168- return ptr ;
185+ if (!nelem || !elsize || nelem > SIZE_MAX / elsize )
186+ return NULL ;
187+ return alloc (TEST_CALLOC , nelem * elsize );
169188}
170189
171190void test_free (void * p )
0 commit comments