-1

Well I've weird problem with printf(). It's outputting garbage on screen. It's kind of connected with memory I guess. Have a look:

char string1[] = "SAMPLE STRING";
char string2[20]; // some garbage in it

/* let's clear this madness*/
int i = 0;
for (i; i < 20; i++) string2[i] = ' ';   // Space, why not.

printf("output: %s", string2);

OUTPUT

output:      ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠SAMPLE STRING
// ten spaces and random characters, why?
Mike
  • 43,847
  • 27
  • 105
  • 174
krzakov
  • 3,441
  • 10
  • 33
  • 48
  • Are you sure it's not *20* spaces and then random characters after that? – Alok Singhal Nov 26 '12 at 15:34
  • ╠ is 0xCC in codepage 437, and [MSVC fills 0xCC to uninitialized memory to help debugging](https://stackoverflow.com/q/370195/995714). That means you've accessed uninitialized memory. You can find tons of questions about ╠ and 0xCC here on SO – phuclv Aug 18 '18 at 10:54

2 Answers2

8

Because C strings need to be NUL terminated. This means the last char of your string must be '\0'. This is how printf (and all other C string functions) know when a string is finished.

Alfonso
  • 8,266
  • 42
  • 63
  • 1
    Actually, they are NUL terminated. NUL is the nul character, NULL is the nul pointer. – rodrigo Nov 26 '12 at 15:36
  • 1
    I would write this as "null-terminated", not "NULL terminated", since `NULL` (all caps) is a pointer, so it could be confusing. – Alok Singhal Nov 26 '12 at 15:36
2

finish your string2 with null character '\0'

string2[19] = '\0';

Or you can do it in this way:

for (i; i < 19; i++) string2[i] = ' ';
string2[i] = '\0'; // after the end of the loop i= 19 here
MOHAMED
  • 38,769
  • 51
  • 148
  • 252