Avoid allocations in string_replace_at when possible.

This commit is contained in:
Yuri D'Elia 2014-12-21 22:14:19 +01:00 committed by Eizen
parent 98566667c7
commit cf910b0683

14
utils.c
View File

@ -25,13 +25,21 @@ char *string_replace_at(char *buf, int pos, int len, const char *repl)
buf_len = strlen(buf); buf_len = strlen(buf);
repl_len = strlen(repl); repl_len = strlen(repl);
size = (buf_len - len) + repl_len + 1; size = (buf_len - len) + repl_len + 1;
tmp = malloc(size);
if (repl_len <= len) {
tmp = buf;
} else {
tmp = malloc(size);
}
memcpy(tmp, buf, pos); memcpy(tmp, buf, pos);
memcpy(tmp + pos, repl, repl_len); memcpy(tmp + pos, repl, repl_len);
memcpy(tmp + pos + repl_len, buf + pos + len, buf_len - (pos + len) + 1); memmove(tmp + pos + repl_len, buf + pos + len, buf_len - (pos + len) + 1);
if(tmp != buf) {
free(buf);
}
free(buf);
return tmp; return tmp;
} }