Hi
I came across this question in C++ Primer by Stanley Lippman.

int
main()
{
      const char ca[] = {'h', 'e', 'l', 'l', 'o'};
      const char *cp = ca;
      while( *cp )
      {
            cout << *cp << endl;
            ++cp;
      }
}

According to me, this code should produce indefinite result because of no specified null character at the end of the string, as the loop would continue until it finds a null character in any memory location.
But when I compiled the code, it runs for EXACLTY 13 times each times. WHy does the loop terminate after 13 iterations? OR Why is the null character present in the 13th memory location EACH TIME?
OR Im just wrong with my concepts, which I think I am.
Do help me.

According to me,

This is an odd phrase. Just saying.

this code should produce indefinite result because of no specified null character at the end of the string

Correct.

Why is the null character present in the 13th memory location EACH TIME?

In practice, it depends on how your compiler generates the stack frame for main() and what direction the pointer is walking along the stack. But the correct answer is that this code invokes undefined behavior, so anything could happen and there's no useful explanation except that the code is broken and needs to be fixed.

What Narue says is entirely correct.


>>WHy does the loop terminate after 13 iterations?

Your stack-frame will look like this: 8 bytes for the char-array (ca) (aligned at 4 bytes, since it needs 5 bytes, it will take up 8 bytes as the smallest multiple of 4 bytes), and 4 bytes for the char-pointer (cp), that makes 12. Your compiler probably fills the stack-frame with some special value (used while debugging), so you hit a 0 only when you reach the end of the stack-frame. But I don't know why the byte after the end of the stack-frame is always zero, that's why they call this undefined behavior. For instance, on my computer, it always stops just after the end of the char-array, as if it was a null-terminated string.

Undefined behavior really just means that there is no way to be sure what will happen, all bets are off. But understanding why it can behave in certain ways is good, because it might help you to recognize the symptoms if you have code with such a problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.