I wrote the following code with the intention of using pointer arithmetic on strings to find, and replace, a targeted substring. Obviously, it's not elegant, but unfortunately it's also incorrect - it adds extraneous characters to the string.
#include <stdio.h>
#include <string.h>
int main() {
char string[] = "The quick brown fox jumped over the lazy dog.";
char target[] = "brown"
char replacement[] = "ochre";
char segment[80+1];
char pre_segment[80+1];
char post_segment[80+1];
int S = strlen(string), T = strlen(target);
for (int i = 0; i < S; i++) {
strncpy(segment, string + i, T);
if (strcmp(segment, target) == 0) {
>>> strncpy(pre_segment, string, i); <<<
strncpy(post_segment, string + i + T,
S - (i + T));
strcat(pre_segment, replacement);
strcat(pre_segment, post_segment);
printf("%s\n", pre_segment);
}
}
return 0;
}
After the line marked like >>>this<<<, extraneous characters have been prepended to replacement before replacement is concatenated with pre_segment.
Can someone give me suggestions on how to debug this? (Suggestions for a nicer solution are also welcome, but please try to be explicit. Also, I'm not supposed to be using dynamic memory allocation for this.)