Using printf
to print "\4unix\5lancs\2ac\2uk\0"
I find, instead of a print in the form of ♦unix♣lancs☻ac☻uk
, I get garbage (♫ ,►E¦§Qh ↕
).
I cannot find an explanation for this; I use the following method to tokenise a string:
/**
* Encode the passed string into a string as defined in the RFC.
*/
char * encodeString(char *string) {
char stringCopy[128];
char encodedString[128] = "";
char *token;
/* We copy the passed string as strtok mutates its argument. */
strcpy(stringCopy, string);
/* We tokenise the string on periods. */
token = strtok(stringCopy, ".");
while (token != NULL) {
char encodedToken[128] = "";
/* Encode the token. */
encodedToken[0] = (char) strlen(token);
strcat(encodedToken, token);
/* Add the encodedString token to the encodedString string. */
strcat(encodedString, encodedToken);
/* Prepare for the next iteration. */
token = strtok(NULL, ".");
}
/* A null character is appended already to the encoded string. */
return encodedString;
}
And the following code in my driver to print the result when tokenising "unix.lancs.ac.uk"
:
int main(int argc, char *argv[]) {
char *foo = "unix.lancs.ac.uk";
char *bar = encodeString(foo);
printf("%s\n", bar);
return 0;
}
If I add a printf
to print encodedString
at the end of the encodeString
method, I don't get garbage printed out (rather, ♦unix♣lancs☻ac☻uk
twice).
(Upon debugging I notice the actual memory contents is changed.)
Can anyone explain this phenomenon to me?