I have the following code
int eval(char* string) {
char* token;
outputString[0] = NULL;
token = strtok(string, " ");
while(token != NULL){
if(strstr((char *) token, "@") != NULL) {
strcat(outputString, "@");
token = calc(token);
}
strcat(outputString, token);
strcat(outputString, " ");
token = strtok(NULL, " ");
}
printf("%s\n", outputString);
}
It is called on a string that looks like this
The water has @TREE and @SKY in it.
This code works completely fine. However I want to make it more efficient.
The code is supposed to do the following --
Cut the string up by spaces, however, if an @
is found, it should be sent away to be evaluated by calc();
. If none are found, we continue splitting the string by spaces until one is actually found. While we are running through, we concatenate it onto outputString and continue forward.
1 Answer 1
outputString
doesn't have enough room to accomodate the results. It can hold just one byte. It is just unlucky coincidence that the code does not segfault. In any case, undefined behaviour.If the intention is just to print the result out, you don't need
outputString
at all. Justprintf
the tokens as you compute them.strcat
must scan the entireoutputString
to figure out where it ends. The overall time complexity of the repeatedstrcat
s becomes roughly quadratic. I recommend to maintain a pointer to the end ofoutputString
, andstrcpy
the token.
aaa@bbb
and similar tokens should be processed? \$\endgroup\$