Add missing memory allocation failure checks.

Inspired by GitHub PR #221
This commit is contained in:
Todd C. Miller
2022-12-15 09:30:49 -07:00
parent e706204f5f
commit 0e6482e827
2 changed files with 26 additions and 7 deletions

View File

@@ -140,11 +140,14 @@ str_array_snprint(char *out_str, size_t max_len, char **str_array, int array_len
char *
str_replaced(const char *source, size_t dest_len, const char *old, const char *new)
{
char *result = calloc(1, dest_len);
char *result = malloc(dest_len);
char *dest = result;
char *pos = NULL;
size_t old_len = strlen(old);
if (result == NULL)
return NULL;
while ((pos = strstr(source, old)) != NULL) {
size_t len = snprintf(dest, dest_len,
"%.*s%s", (int)(pos - source), source, new);
@@ -170,6 +173,8 @@ void
str_replace_in_place(char *string, size_t max_length, const char *old, const char *new)
{
char *replaced = str_replaced(string, max_length, old, new);
strlcpy(string, replaced, max_length);
free(replaced);
if (replaced != NULL) {
strlcpy(string, replaced, max_length);
free(replaced);
}
}