Skip to content

Implement test_realloc #284

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions harness.c
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ static bool time_limited = false;
typedef enum {
TEST_MALLOC,
TEST_CALLOC,
TEST_REALLOC,
} alloc_t;

/* Internal functions */
Expand Down Expand Up @@ -128,6 +129,7 @@ static void *alloc(alloc_t alloc_type, size_t size)
char *msg_alloc_forbidden[] = {
"Calls to malloc are disallowed",
"Calls to calloc are disallowed",
"Calls to realloc are disallowed",
};
report_event(MSG_FATAL, "%s", msg_alloc_forbidden[alloc_type]);
return NULL;
Expand All @@ -137,6 +139,7 @@ static void *alloc(alloc_t alloc_type, size_t size)
char *msg_alloc_failure[] = {
"Malloc returning NULL",
"Calloc returning NULL",
"Realloc returning NULL",
};
report_event(MSG_WARN, "%s", msg_alloc_failure[alloc_type]);
return NULL;
Expand Down Expand Up @@ -187,6 +190,28 @@ void *test_calloc(size_t nelem, size_t elsize)
return alloc(TEST_CALLOC, nelem * elsize);
}

/*
* Implementation of adjusting the size of the memory allocated
* by test_malloc or test_calloc.
*/
void *test_realloc(void *p, size_t new_size)
{
if (!p)
return alloc(TEST_REALLOC, new_size);

const block_element_t *b = find_header(p);
if (b->payload_size >= new_size)
return p;

void *new_ptr = alloc(TEST_REALLOC, new_size);
if (!new_ptr)
return NULL;
memcpy(new_ptr, p, b->payload_size);
test_free(p);

return new_ptr;
}

void test_free(void *p)
{
if (noallocate_mode) {
Expand Down
3 changes: 2 additions & 1 deletion harness.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@

void *test_malloc(size_t size);
void *test_calloc(size_t nmemb, size_t size);
void *test_realloc(void *p, size_t new_size);
void test_free(void *p);
char *test_strdup(const char *s);
/* FIXME: provide test_realloc as well */

#ifdef INTERNAL

Expand Down Expand Up @@ -56,6 +56,7 @@ void trigger_exception(char *msg);
/* Tested program use our versions of malloc and free */
#define malloc test_malloc
#define calloc test_calloc
#define realloc test_realloc
#define free test_free

/* Use undef to avoid strdup redefined error */
Expand Down
Loading