Skip to content

Commit 9a84764

Browse files
authored
Fix memory leak when adding the same key to the logger hash map multiple times (ros2#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>
1 parent c83c4c7 commit 9a84764

1 file changed

Lines changed: 14 additions & 7 deletions

File tree

src/logging.c

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -771,13 +771,20 @@ int rcutils_logging_get_logger_level(const char * name)
771771

772772
static rcutils_ret_t add_key_to_hash_map(const char * name, int level, bool set_by_user)
773773
{
774-
// Copy the name that we will store, as there is no guarantee that the caller will keep it around.
775-
776-
char * copy_name = rcutils_strdup(name, g_rcutils_logging_allocator);
777-
if (copy_name == NULL) {
778-
// Don't report an error to the error handling machinery; some uses of this function are for
779-
// caching so this is not necessarily fatal.
780-
return RCUTILS_RET_ERROR;
774+
const char * copy_name = name;
775+
// Check if key already exists, to avoid extra memory allocation
776+
// If the key already exists, then rcutils_hash_map_set will not maintain the key we give it,
777+
// so we do not need to copy the name
778+
bool already_exists = rcutils_hash_map_key_exists(&g_rcutils_logging_severities_map, &copy_name);
779+
780+
if (!already_exists) {
781+
// Copy the name to be stored, as there is no guarantee that the caller will keep it around.
782+
copy_name = rcutils_strdup(name, g_rcutils_logging_allocator);
783+
if (copy_name == NULL) {
784+
// Don't report an error to the error handling machinery; some uses of this function are for
785+
// caching so this is not necessarily fatal.
786+
return RCUTILS_RET_ERROR;
787+
}
781788
}
782789

783790
if (set_by_user) {

0 commit comments

Comments
 (0)