This could happen when the "token"
string ends up at the beginning of the string after the removal of the square brackets: in this case, (size_t)(found - src)
evaluates to zero, so the call of
strncpy(res, src, (size_t)(found - src));
does not change the res
string at all, leaving whatever junk that was there for the following call of strcat
to skip before appending. You get lucky that the junk in the res
happens to be a short null-terminated string, such as an "X"
or an "H"
. Otherwise, you could get a much longer string of arbitrary characters.
In addition to fixing the above undefined behavior, you should fix a few more things:
- Your code does not check the return value of the first
malloc
. - Your code miscalculates the length of the result: you should subtractl the length of the word
"token"
, because you replace it with the content ofrepl
, i.e. it should bemalloc(strlen(src) + strlen(repl) - strlen(find) + 1)
- You do not need to cast the return value of
malloc
in C - You do not need to multiply the length by
sizeof(char)
(only one of your twomalloc
s does that) - Your second early return leaks memory.