Skip to content
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

Fix memory leak when adding the same key to the logger hash map multiple times #391

Merged
merged 3 commits into from
Oct 13, 2022
Merged
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
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