This smells like a heap corruption of some kind but I can not seem to find it.
the problem occurs on string_utils_replace()
when trying to run free(tmp_for_free)
. the function is supposed to replace every occurrence of "search"
with "replace"
in "string"
.
char* string_utils_part_of_string(char *string, int from, int to)
{
int size_to_allocate = to - from + 1;
char *result = (char*)malloc(sizeof(char) * size_to_allocate);
strncpy(result, string + from, to - from);
result[size_to_allocate - 1] = '\0';
return result;
}
char* string_utils_replace(char *search, char *replace, char *string)
{
char *end, *result = string, *tmp_for_free = NULL;
int before_replace, after_replace;
int size_search = strlen(search);
int size_replace = strlen(replace);
int size_string, size_find;
int first_time = 1;
char *find = strstr(string, search);
if (find == NULL)
return string_utils_copy_string(string);
while (find != NULL)
{
tmp_for_free = result;
size_string = strlen(result);
size_find = strlen(find);
before_replace = size_string - size_find;
after_replace = before_replace + size_replace;
end = string_utils_part_of_string(result, after_replace, size_string);
result = string_utils_part_of_string(result, 0, before_replace);
strcat(result, replace);
strcat(result, end);
// no memory leaks, hooray!
free(end);
if (first_time == 0)
free(tmp_for_free);
size_string = strlen(result);
find = strstr(result, search);
first_time = 0;
}
return result;
}
any ideas?