I have a loop running to add spaces between some special characters (&,|,<,>). The following code successfully adds spaces before and after a special character:
char keys[] = "<>&|";
int i = strcspn (input,keys);
appenda(input, " " , i);
appenda(input, " " , i+2);
The above code converts input “asdf&asdf” to “asdf & asdf”.
However, my goal is to do that for every special character in the entire input even with multiple special characters (like “asdf&asdf&asdf”). So I made a while loop:
char keys[] = "<>&|";
int i = strcspn (input,keys);
while(i < strlen(input)){
appenda(input, " " , i);
appenda(input, " " , i+2);
i = strcspn (input,keys);
}
Yet, when I run my code now, it returns with “*** stack smashing detected ***“
Any Ideas on what this means and how to get around it?
EDIT
Appenda inserts a string into another string at a designated point. it takes in 3 arguments: 1st is a string which i insert into, 2nd is a string which i want to insert and 3rd is the index. so appenda(ABCD, X, 2) returns AXBCD
You’re always calling
strcspnon the sameinput, and you’re never actually removing the characters that it’s finding, so it is always finding the same one.For example, if your string is
The first call to
Returns
i = 3since the&is in position 4. Then you insert the spaces, which works fine, and the string becomes:Now you again call
And this returns
i = 4because now it finds the first&in position 5. So when you insert spaces again the string becomes:And so on. It keeps inserting more and more spaces around the first
&, and the loop never ends until you overrun the buffer insideappendaand your program dies.Instead, once you’ve inserted spaces, you need to tell
strcspnto start looking for the next special character past the place where you found the previous one. This should work:This “moves” the value of
isuch that when you callstrcspn(input + i, keys), the valueinput + ialways refers to the next position that has not yet been looked at for special characters.