I'm on week 4 and looking over other people's codes and I've noticed that up to this point, I've never really nul-terminated strings with '\0'. From what I understand, there are some functions where the nul byte is added for you.

For example,

char* word1 = "hello";
char word2[5] = "hello";
char word3[6] = "hello";
char word4[] = "hello";

In which of these declarations is the string nul terminated?


"In which of these declarations is the string nul terminated?"

All of them. But that doesn't mean that they're ok.

In each of them, a variable is being declared and initialized with a string. You can usually assume that anytime a string is being written somewhere, the end of string marker (EOS) is being written too.

Three of your examples will work fine. However, one will cause problems. char word2[5] = "hello"; has a serious issue. It allocates 5 chars where 6 are needed. When a string is copied into this array, it'll write the whole string, including the EOS marker, regardless of how much space is allocated to the string. That means that the 6th byte of memory will contain the EOS marker. Unfortunately, that memory is not allocated to this string, so whatever it IS allocated to will be overwritten and corrupted.

Now, if you are copying char by char, say perhaps with a for loop, then you would have to manually make sure to insert the EOS marker, either by copying an existing one or by directly writing one in. Same rule applies to copying SUBstrings.

Pay careful attention when copying substrings. For example, strncpy() can be used to copy a substring into the middle of another string. To make this work right, it will not insert an EOS marker into the target string. (I'm not entirely sure if it will or will not add the EOS marker if the added substring causes the end of the added substring to actually be the end of the target string, so best to deal with that in code.)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .