I'm having problemes with a function which should replace every character c in the given char array src with the char array text.
first I calculate the length of the return value. Then I insert the correct chars. At least thats what i try.
The problem is I am having unexpected behaviour at the return value. sometimes it replaces only the first matching letter. sometimes is is replacing every an adding one cryptic letter.
char *myreplace(const char *src, char c, const char *text){
int mylength=0;
for(int i=0; src[i] != '\0'; i++){
if(src[i] == c)
for(int j=0; text[j] != '\0'; j++){
++mylength;
}
else
++mylength;
}
char *newtext=new char[mylength+1];
int x=0;
for(int i=0; src[i] != '\0'; i++){
if(src[i] == c)
for(int j=0; text[j] != '\0'; j++){
newtext[i+x] = text[j];
++x;
}
else
newtext[i+x]=src[i];
}
return newtext;
}
When you replace one character with your replacement string, you effectively double increment (both
iandx), resulting in skipping one character for each replaced instance and writing past the end of the allocated buffer.Let's look at an example:
srcis "abc",textis "d", andchis 'a'.When we replace the first character, we write the
dtonewtextand incrementx. The next time thru the loop, we write the second source character ('b') tonewtext[i+x], ornewtext[2]when it should go tonewtext[1].The simplest fix is to decrement
xby 1 after copying in the replacement string.You're also not writing the terminating nul character
'\0'to the end of yournewtextstring. (Addnexttext[x+i] = 0;before the return.)