Reputation: 622
I'm running into an odd problem with concatenating or printing strings. I have a char * that can be set to one of a few values of string literal.
char *myStrLiteral = NULL;
...
if(blah)
myStrLiteral = "foo";
else if(blahblah)
myStrLiteral = "bar";
And I have some other strings that I get from library functions or that are concatenations of input - they're either malloc'ed or stack variables. When I try to print (or concatenate using strcpy() and strcat(), the result is the same), even though I print the string literal last, it prints over the initial characters of the entire string I'm constructing or printing.
/* otherString1 contains "hello", otherString2 contains "world" */
printf("%s %s %s\n", otherString1, otherString2, myStrLiteral);
/* prints "barlo world" */
Am I misunderstanding something about string literals in C?
Upvotes: 2
Views: 2603
Reputation: 7799
The only thing I can think of is that the otherString2 contains a carriage return, but not a line feed.
to find out
Upvotes: 2
Reputation: 200996
Check that the literals you're receiving contain only the bytes you expect:
void PrintBytes(const char *s)
{
while (*s) {printf("%d ", *s); s++;}
}
PrintBytes(otherString1);
PrintBytes(otherString2);
PrintBytes(myStrLiteral);
My suspicion is that one of them contains an embedded control character.
If you don't care about finding out which control character is involved, you could simply print the length of each string. If it's longer than it ought to be, there's a control character in there somewhere:
printf("%d\n%s\n", strlen(otherString1), otherString1);
Upvotes: 4