Reputation: 1556
I was making a basic program of strings and did this. There is a string in this way:
#include<stdio.h>
int main()
{
char str[7]="network";
printf("%s",str);
return 0;
}
It prints network
.In my view, it should not print network. Some garbage value should be printed because '\0'
does not end this character array. So how it got printed? There were no warning or errors too.
Upvotes: 2
Views: 147
Reputation: 927
It's possible that stack pages start off completely zeroed in your system, so the string is actually null-terminated in memory, but not thanks to your code.
Try looking at the program in memory using a debugger, reading your platform documentation or printing out the contents of str[7]
to get some clues. Doing so invokes undefined behavior but it's irrelevant when you're trying to figure out what your specific compiler and OS are doing at one given point in time.
Upvotes: 0
Reputation: 122383
That's because
char str[7]="network";
is the same as
char str[7]={'n','e','t','w','o','r','k'};
str
is a valid char
array, but not a string, because it's no null-terminated. So it's undefined behavior to use %s
to print it.
Reference: C FAQ: Is char a[3] = "abc"; legal? What does it mean?
Upvotes: 3
Reputation: 1181
char str[7]="network";
you did not provide enough space for the string
char str[8]="network";
Upvotes: 0
Reputation: 10516
char str[7]="network";
This Invokes Undefined behavior
.
You did not declared array with enough space
This should be
char str[8]="network";
Upvotes: 3