Skip to content

Commit

Permalink
Fix memory leak when adding the same key to the logger hash map multi…
Browse files Browse the repository at this point in the history
…ple times (#391)

The first time a key is added the hash map will retain a copy of the pointer and later will deallocate the memory during shutdown.
Subsequent times the same key is added to the hash map, it will NOT retain a copy of the new pointer, and hence not deallocate the
memory during shutdown.

This fixes the issue by checking if we're adding an entry for an existing key and if so, avoid allocating new memory.

Signed-off-by: Jacob Perron <jacob@openrobotics.org>
  • Loading branch information
jacobperron authored Oct 13, 2022
1 parent c83c4c7 commit 9a84764
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/logging.c
Original file line number Diff line number Diff line change
Expand Up @@ -771,13 +771,20 @@ int rcutils_logging_get_logger_level(const char * name)

static rcutils_ret_t add_key_to_hash_map(const char * name, int level, bool set_by_user)
{
// Copy the name that we will store, as there is no guarantee that the caller will keep it around.

char * copy_name = rcutils_strdup(name, g_rcutils_logging_allocator);
if (copy_name == NULL) {
// Don't report an error to the error handling machinery; some uses of this function are for
// caching so this is not necessarily fatal.
return RCUTILS_RET_ERROR;
const char * copy_name = name;
// Check if key already exists, to avoid extra memory allocation
// If the key already exists, then rcutils_hash_map_set will not maintain the key we give it,
// so we do not need to copy the name
bool already_exists = rcutils_hash_map_key_exists(&g_rcutils_logging_severities_map, &copy_name);

if (!already_exists) {
// Copy the name to be stored, as there is no guarantee that the caller will keep it around.
copy_name = rcutils_strdup(name, g_rcutils_logging_allocator);
if (copy_name == NULL) {
// Don't report an error to the error handling machinery; some uses of this function are for
// caching so this is not necessarily fatal.
return RCUTILS_RET_ERROR;
}
}

if (set_by_user) {
Expand Down

0 comments on commit 9a84764

Please sign in to comment.