I'm trying to make a function in C to replace all occurrences of a substring in a string. I made my function, but it only works on the first occurrence of the substring in the bigger string.
Here is the code so far:
void strreplace(char string[], char search[], char replace[]){
char buffer[100];
char*p = string;
while((p=strstr(p, search))){
strncpy(buffer, string, p-string);
buffer[p-string] = '\0'; //EDIT: THIS WAS MISSING
strcat(buffer, replace);
strcat(buffer, p+strlen(search));
strcpy(string, buffer);
p++;
}
}
For starters:
This line
strncpy(buffer, string, p-string);
not necessarily appends a 0
-terminator to what had been copied to buffer
.
The following line
strcat(buffer, replace);
however relies on buffer
being 0
-terminated.
As buffer
had not been initialised and though the 0
-terminator most likely misses the latter line may very well read beyond buffer
's memory and with this invoke the infamous Undefined Behaviour.