+ 2
Output in C
Why the below code show output as "hep@" When I didn't provide a space or room for null terminator in char array? https://code.sololearn.com/c1ChyZWGSH3C/?ref=app
5 ответов
+ 2
Well, memory is just 1 huge array, your "he" array are just 2 bytes within that array that is shared with a lot of other data.
Your memory could contains bytes like for example:
10 00 00 00 00 00 68 65 50 40 00 00 00 00 etc ( hexadecimal )
In this example your array is stored within this array, the "68 65" part represent your array in this case. ('h' = 68, 'e' = 65 ).
As you can see there is no 00 ( \0, the null character ) following this data.
Since the "%s" format specifier means "Read data until you find a null character" it now starts reading from the 68 part, 1 byte at a time.
So it prints 68('h'), 65('e'), 50('P'), 40('@') and only now it encounters the 00('\0') and it's done.
That 50 40 00 00 is just different data associated to your program which could mean anything. In other words accessing it is undefined behavior, the data there can be anything.
I looked through a debugger and in this case it's just pushed there by the setup of the stack frame of the main function and the data represents a pointer that points to the name of the file. ( at least on my compiler ).
But that's not very important, just trying to say you probably don't want to access data out of bounds like this.
+ 5
Because a "p@\0" just happened to be stored in memory after "he".
printf just happily keeps going till it finds any null character or until it crashes, whatever happens first.
+ 2
THANKS Dennis and codemonkey.☺
+ 2
Dennis please can you define it detaily.Because I won't understand clearly
+ 2
Thank you Dennis for your explanation.
Now I understand why this output comes:)