0

Although my array is only of size 3, and I've assigned a char to each element, a NULL Terminator is still automatically added. What is causing a NULL Terminator to be added in my code?

int main(void)
{
    char s[3];
    s[0] = 'f';
    s[1] = 'o';
    s[2] = 'o';

    int i = 0;

    while (s[i] != '\0')
        printf("%c", s[i++]);

    printf("\n");

    if (s[i] == '\0')
        printf("Null Terminator Added\n");
}   
de3z1e
  • 411
  • 4
  • 8
  • 4
    it's just good ol' undefined behavior. a 0 *happens to be present* after your array, but that's just bad luck. – The Paramagnetic Croissant Nov 22 '14 at 19:21
  • "What is causing a NULL Terminator to be added in my code" - Good chance it's the `i = 0` (although I would expect a gap of 1 byte between them). You can check `&i` if you want to verify that, but in general it's not guaranteed by the language that the compiler will allocate `i` immediately after `s`. It's just a matter of luck, as to the contents of the stack at the point in execution where your function is called (in your specific example it's `main`, so you should expect the same result upon every execution). – barak manos Nov 22 '14 at 19:27
  • If you are relatively new to C, and having issues with how arrays and pointers work, here is an answer that helps visualize the difference: http://stackoverflow.com/questions/27052988/what-is-the-difference-between-different-kinds-of-pointer-in-c/27054973#27054973 – technosaurus Nov 22 '14 at 20:03
  • Thanks for all the helpful feedback. After some further testing I came to the same conclusion. The '/0' coincidentally just happened to be in the undefined s[3] memory location of the stack. – de3z1e Nov 22 '14 at 22:12
  • `NULL` is (a macro that expands to) a null *pointer* constant. Don't use the term "NULL" to refer to the null character. – Keith Thompson Nov 22 '14 at 22:21

1 Answers1

3

It's not "automatically added". When you try to access s[3], you are accessing memory that's not part of the array s. On your machine, it appears that this memory happens to contain a null byte. You can't rely on that happening; maybe on another machine, or another run, that memory will happen to contain something else. Or maybe the computer will detect an illegal memory access and your program will crash. Or maybe your program will break in some other subtle and unexpected way.

Short answer: your program is buggy, and you can't really draw any meaningful conclusions from its behavior.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82