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 common realloc mistake in custom_output_search_replace.c #931

Merged
merged 1 commit into from
Sep 27, 2016
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
48 changes: 28 additions & 20 deletions src/shared/custom_output_search_replace.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ char *searchAndReplace(const char *orig, const char *search, const char *value)

size_t inx_start;
char *tmp = NULL;
char *tmp2 = NULL;
size_t tmp_offset = 0;
size_t total_bytes_allocated = 1;
size_t from;
Expand All @@ -36,29 +37,36 @@ char *searchAndReplace(const char *orig, const char *search, const char *value)
while (p != NULL) {
/* Copy replacement */
total_bytes_allocated += value_len;
tmp = (char *) realloc(tmp, total_bytes_allocated);
strncpy(tmp + tmp_offset, value, value_len);
tmp_offset += value_len;

/* Search for further occurrences */
p = strstr(orig + inx_start + search_len, search);
if (p != NULL) {
size_t inx_start2 = (size_t) (p - orig);

/* Copy content between matches, if any */
if (inx_start2 > from) {
size_t gap = inx_start2 - from;
total_bytes_allocated += gap;
tmp = (char *) realloc(tmp, total_bytes_allocated);
strncpy(tmp + tmp_offset, orig + from, gap);
tmp_offset += gap;
tmp2 = (char *) realloc(tmp, total_bytes_allocated);

if (tmp2 != NULL) {
tmp = tmp2;
strncpy(tmp + tmp_offset, value, value_len);
tmp_offset += value_len;

/* Search for further occurrences */
p = strstr(orig + inx_start + search_len, search);
if (p != NULL) {
size_t inx_start2 = (size_t) (p - orig);

/* Copy content between matches, if any */
if (inx_start2 > from) {
size_t gap = inx_start2 - from;
total_bytes_allocated += gap;
tmp = (char *) realloc(tmp, total_bytes_allocated);
strncpy(tmp + tmp_offset, orig + from, gap);
tmp_offset += gap;
}

inx_start = inx_start2;
}

inx_start = inx_start2;
/* Set position for copying content after last match */
from = inx_start + search_len;
} else {
free(tmp);
/* And handle error */
}

/* Set position for copying content after last match */
from = inx_start + search_len;
}

/* Copy content after last match, if any */
Expand Down