-2
int main()
{
char btext[20];

for(int i=0; i< sizeof(btext); i++)
    {
        btext[i]= 'x' ;
    }

for(int i=0; i< sizeof(btext); i++)
    {
        printf("%c", btext[i]);
    }

printf("\nbtext: %s\n", btext);

return 0;
}

This gives the output:

xxxxxxxxxxxxxxxxxxxx

btext: xxxxxxxxxxxxxxxxxxxx?

Where does that ? come from? And even worse:

int main()
{
char text[] = "some text";

char btext[20];

printf("text: %s\n", text);

for(int i=0; i< sizeof(btext); i++)
    {
        btext[i]= 'x' ;
    }

for(int i=0; i< sizeof(btext); i++)
    {
        printf("%c", btext[i]);
    }

printf("\nbtext: %s\n", btext);

return 0;
}

This gives the output:

text: some text xxxxxxxxxxxxxxxxxxxx

btext: xxxxxxxxxxxxxxxxxxxxsome text

This drives me crazy. The code is so straightforward, but I can't figure it out. Is it a bug in the IDE? Has anyone seen something like this?

Bolle Sat
  • 11
  • 2
  • C strings are terminated by the [NUL character](https://en.wikipedia.org/wiki/Null_character). Set the last character of `btext` to zero. – Cornstalks Apr 22 '18 at 21:39
  • That is most probably a buffer overflow. Have a look [here](https://security.stackexchange.com/questions/43574/how-is-printf-in-c-c-a-buffer-overflow-vulnerability) – Dhruv Sehgal Apr 22 '18 at 21:43
  • 1
    Please don't edit your question to keep changing the code. You were originally using the variable name `Btext`. Then you unnecessarily edited it to `btext`. Your edit invalidated my comment and 2 answers (because we were using the identifier `Btext`). – Cornstalks Apr 22 '18 at 21:43
  • *facepalm* that was actually part of a task-position. I didn't even consider them to make a mistake like that. Thanks! – Bolle Sat Apr 22 '18 at 21:53

1 Answers1

1

You never NULL-terminate your string. Try:

Btext[sizeof(Btext)-1] = '\0';

Before printing the string out.

mnistic
  • 10,866
  • 2
  • 19
  • 33