Output in C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

1st Aug 2020, 12:27 PM
Yogeshwaran P
Yogeshwaran P - avatar
5 Answers
+ 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.
1st Aug 2020, 1:37 PM
Dennis
Dennis - avatar
+ 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.
1st Aug 2020, 12:32 PM
Dennis
Dennis - avatar
+ 2
THANKS Dennis and codemonkey.☺
1st Aug 2020, 1:01 PM
Yogeshwaran P
Yogeshwaran P - avatar
+ 2
Dennis please can you define it detaily.Because I won't understand clearly
1st Aug 2020, 1:03 PM
Yogeshwaran P
Yogeshwaran P - avatar
+ 2
Thank you Dennis for your explanation. Now I understand why this output comes:)
1st Aug 2020, 1:43 PM
Yogeshwaran P
Yogeshwaran P - avatar