Skip to content

Commit

Permalink
Define behavior of malloc(0)
Browse files Browse the repository at this point in the history
Some systems may return either NULL or a valid pointer on malloc(0).  c-ares should never call malloc(0) so lets return NULL so we're more likely to find an issue if it were to occur.
  • Loading branch information
bradh352 committed Dec 24, 2020
1 parent 3c0bc07 commit 485fb66
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/lib/ares_library_init.c
Expand Up @@ -40,13 +40,18 @@ static unsigned int ares_initialized;
static int ares_init_flags;

/* library-private global vars with visibility across the whole library */

/* Some systems may return either NULL or a valid pointer on malloc(0). c-ares should
* never call malloc(0) so lets return NULL so we're more likely to find an issue if it
* were to occur. */

static void *default_malloc(size_t size) { if (size == 0) { return NULL; } return malloc(size); }

#if defined(WIN32)
/* We need indirections to handle Windows DLL rules. */
static void *default_malloc(size_t size) { return malloc(size); }
static void *default_realloc(void *p, size_t size) { return realloc(p, size); }
static void default_free(void *p) { free(p); }
#else
# define default_malloc malloc
# define default_realloc realloc
# define default_free free
#endif
Expand Down
2 changes: 1 addition & 1 deletion test/ares-test.cc
Expand Up @@ -135,7 +135,7 @@ bool LibraryTest::ShouldAllocFail(size_t size) {

// static
void* LibraryTest::amalloc(size_t size) {
if (ShouldAllocFail(size)) {
if (ShouldAllocFail(size) || size == 0) {
if (verbose) std::cerr << "Failing malloc(" << size << ") request" << std::endl;
return nullptr;
} else {
Expand Down

0 comments on commit 485fb66

Please sign in to comment.