iemejia commented on code in PR #3858:
URL: https://github.com/apache/avro/pull/3858#discussion_r3567452871


##########
lang/c/src/map.c:
##########
@@ -106,16 +106,31 @@ int avro_raw_map_get_or_create(avro_raw_map_t *map, const 
char *key,
                el = (char *) raw_entry + sizeof(avro_raw_map_entry_t);
                is_new = 0;
        } else {
+               char  *key_copy;
+               size_t  key_size;
                i = map->elements.element_count;
                avro_raw_map_entry_t  *raw_entry =
                    (avro_raw_map_entry_t *) 
avro_raw_array_append(&map->elements);
-               raw_entry->key = avro_strdup(key);
-               st_insert((st_table *) map->indices_by_key,
-                         (st_data_t) raw_entry->key, (st_data_t) i);
                if (!raw_entry) {
-                       avro_str_free((char*)raw_entry->key);
+                       /* avro_raw_array_append returns NULL on allocation
+                        * failure; check before dereferencing it. */
+                       return -ENOMEM;
+               }
+               /* Duplicate the key with a NULL-safe allocation: avro_strdup()
+                * memcpy()s into the buffer without checking it, so it would
+                * crash on OOM. Only index the entry once the copy succeeds; on
+                * failure, roll back the element we just appended so the map is
+                * not left with a half-initialized (NULL-key) entry. */
+               key_size = strlen(key) + 1;
+               key_copy = avro_str_alloc(key_size);
+               if (!key_copy) {
+                       map->elements.element_count--;
                        return -ENOMEM;
                }
+               memcpy(key_copy, key, key_size);
+               raw_entry->key = key_copy;
+               st_insert((st_table *) map->indices_by_key,
+                         (st_data_t) raw_entry->key, (st_data_t) i);

Review Comment:
   Filed as AVRO-4305 (https://issues.apache.org/jira/browse/AVRO-4305) to 
track making st_insert() OOM-safe separately.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to