Skip to content

Commit

Permalink
memcpy/memset fixes
Browse files Browse the repository at this point in the history
- `xmalloc`: Check return of `amalloc()` before using `memset()`/`memcpy()` because it's undefined behavior on null pointers
  • Loading branch information
jelu committed Jul 4, 2023
1 parent 128339c commit 46b1797
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/xmalloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -162,21 +162,27 @@ void* amalloc(size_t size)

void* acalloc(size_t number, size_t size)
{
void* p;
size *= number;
p = amalloc(size);
return memset(p, 0, size);
void* p = amalloc(size * number);
if (p)
memset(p, 0, size * number);
return p;
}

void* arealloc(void* p, size_t size)
{
return memcpy(amalloc(size), p, size);
void* r = amalloc(size);
if (p)
memcpy(r, p, size);
return r;
}

char* astrdup(const char* s)
{
size_t size = strlen(s) + 1;
return memcpy(amalloc(size), s, size);
char* p = amalloc(size);
if (p)
memcpy(p, s, size);
return p;
}

void afree(void* p)
Expand Down

0 comments on commit 46b1797

Please sign in to comment.