Mario Bujnak
Mario Bujnak

Reputation: 85

printf("%s") returning weird values

I've got a function which does some stuff with strings, however it has to save the original string by copying it into a char array, making it all upper-case and substitute any w/W for V.

char* function(const char* text){

  int textLength = strlen(text);
  char text_copy[textLength];

  for(int i = 0; i < textLength; i++){
    if(text[i] == 'W' || text[i] == 'w')
      text_copy[i] = 'V';
    else
      text_copy[i] = toupper(text[i]);
  }

  return 'a';
}

It doesn't really matter what the function returns, however whenever I try to printf("%s\n", text_copy);, with some strings, it returns this:

belfast: BELFAST
please: PLEASE
aardvark: AARDVARK??
hello world: HELLO VORLD
taxxxiii: TAXXXIII???
swag: SVAG?

Why is it that some strings turn out fine and some don't? Thanks.

Upvotes: 0

Views: 317

Answers (2)

ysth
ysth

Reputation: 98388

You need to null-terminate the copy.

char text_copy[textLength+1];
...
text_copy[textLength]='\0';

Though if you are returning it from your function (that isn't clear) you should be mallocing it instead.

Upvotes: 3

JeremyP
JeremyP

Reputation: 86651

Why is it that some strings turn out fine and some don't?

Pure chance.

You only allocate enoufgh space for the visible characters in the string and not the terminating \0. You are just lucky that for some of the strings a null byte is on the stack just after the character array.

Change your code like so...

int textLength = strlen(text);
char text_copy[textLength + 1]; // << enough space for the strings and \0

for(int i = 0; i < textLength; i++){
  if(text[i] == 'W' || text[i] == 'w')
    text_copy[i] = 'V';
  else
    text_copy[i] = toupper(text[i]);
}
text_copy[textLength] = '\0'; // Make sure it is terminated properly.

Upvotes: 1

Related Questions