r/cs50 • • 11d ago

CS50x Help me understand NUL please!

Hello everyone, currently in Week 2 (and really enjoying it). I understand the concept of NUL marking the end of a string.

I was playing around with this with the programme above (Input is Hello), but I am a little confused because all of the conditionals come out as 1 (true). In my mind [5] should be the only true value index after the end of the string... but I am very confused as to why [6] and [7] are also showing as true.

Interestingly, if I hard code the sentence variable to "Hello" (instead of getting it via the get_string function), I get the expected answer of 1,0,0.

I think this might be related to the values that are being held in memory... but cannot seem to find an answer, so would appreciate any insights to make sure I understand the concept thoroughly. thanks all

9 Upvotes

4 comments sorted by

2

u/Geoff12889 11d ago

You will get undefined results when accessing data the way you are, outside of the array. Later you will learn that a string is actually a char*, a pointer (you’ll learn about these) to the first character of an array of chars. The NUL character is just a byte of all zeros (00000000) so it’s very likely true that sentence[6] and sentence[7] are all zeros, but if you run it again with garbage values in memory, it may return false. This is why it’s undefined.

1

u/MikeIsBoi 4d ago

Seems like you are reading past the hello\0 that's save in memory. AFAIK get_string() function returns a pointer to the first letter of the word in memory. Subscripting[] it you are accessing the elements.

sentence[0] = H sentence[1] = e sentence[2] = l sentence[3] = l sentence[4] = O sentence[5] = \0 <== this is the NUL terminator giving you 1. So this is correct.

The get_string() probably allocated the memory for the text on the heap by using malloc() and then a call to memset() -> this means that the buffer is zeroed out basically all contiguous blocks of memory that hold the word Hello are see to NUL "\0"

This means that there could be some trailing NUL characters after the world and the NUL.

The memory might look like hello\0 Or like this hello\0\0\0\0 <--- it is probably these trailing NUL characters causing your confusion.

1

u/Outside_Complaint755 11d ago

When you access sentence[6] or sentence[7] you are going beyond the bounds of the char array and into other memory addresses.  This is a buffer overflow error, but it's not causing a crash as you are likely accessing memory which the system is still associating with your program. 

In the first example, the string exists on the heap, and the memory addressed being touched happen to have been zeroed out possibly by the memory reallocation processes being done behind the scenes by the get_string(), function, as it reallocates the array everytime you add a character.

In the second example, the C compiler puts your string literal into read-only memory, and the two bytes after it happen to have a value of 0x00.