Avoid allocations in string_replace_at when possible.
This commit is contained in:
parent
98566667c7
commit
cf910b0683
10
utils.c
10
utils.c
@ -25,13 +25,21 @@ char *string_replace_at(char *buf, int pos, int len, const char *repl)
|
||||
buf_len = strlen(buf);
|
||||
repl_len = strlen(repl);
|
||||
size = (buf_len - len) + repl_len + 1;
|
||||
|
||||
if (repl_len <= len) {
|
||||
tmp = buf;
|
||||
} else {
|
||||
tmp = malloc(size);
|
||||
}
|
||||
|
||||
memcpy(tmp, buf, pos);
|
||||
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);
|
||||
}
|
||||
|
||||
return tmp;
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user