简体   繁体   中英

concatenating/printing a string literal

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?

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);

The only thing I can think of is that the otherString2 contains a carriage return, but not a line feed.

to find out

  1. You can strlen otherString2 and see if it matches what you see
  2. You can look at otherString2 with a debugger and see if 0x0D is before the 0x00 terminating the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM