-4
int main()
{
    char str[2];
    strcpy(str,"0123456789");
    for (int i=0;str[i]!='\0';i++)
    {
        printf("%c %d \n",str[i],i);

    }

    return 0;
}

Not sure how this works but it does not crash. Given that the array has been declared to contain just 2 elements, How does it hold the whole "0-9" elements and prints out the following: 0 0 ,1 1 ,2 2 ,3 3 ,4 4 ,5 5 ,6 6 ,7 7 ,8 8 ,9 9

indiv
  • 17,306
  • 6
  • 61
  • 82
Angelo
  • 61
  • 1
  • 8
  • It *doesn't* work. "Work" doesn't mean what you seem to believe it does. – Kerrek SB Sep 13 '14 at 23:05
  • Memory is allocated to a process in chunks. There is simply enough extra space for it not to crash. It's still technically "undefined behavior", though. – ooga Sep 13 '14 at 23:06
  • Undefined Behavior is undefined. – David G Sep 13 '14 at 23:06
  • Yes I was thinking the same. The standard says its undefined but is the compiler doing some sort of optimisation. If I put a char str[1] it crashes but the moment i do char str[2] it works fine..Weird behaviour – Angelo Sep 13 '14 at 23:07
  • 2
    Two of the answers use the British spelling "undefined behaviour". I mention this only because the US spelling "undefined *behavior*" might work better for searches. In particular, the [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) uses the US spelling (the link is to a recent draft). – Keith Thompson Sep 13 '14 at 23:15
  • @Keith Thompson [LSNED](http://lsned.com/) – chux - Reinstate Monica Sep 13 '14 at 23:28
  • You're missing `#include ` and `#include `. – Keith Thompson Sep 14 '14 at 00:14

2 Answers2

2

This is undefined behavior: more characters are copied into str than it can hold. (Un)fortunately, the program does not crash; it does not make it right, though.

Precisely this issue (incorrect programs appearing to work fine) is a major obstacle in debugging C code: programmers do not detect invalid behavior simply by running a program. One way to deal with this is to run your program through a memory profiler, such as valgrind. This tool will immediately tell you that the program has performed an invalid operation that needs to be fixed.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Because undefined behaviour. You are rather unlucky that your compiler lets you get away with that. A different runtime environment, or some other variables on the stack, or a different compiler will easily yield a different result.

(The technical explanation is: there just so happens to be no user-visible objects after your str array on the stack, so you write past the end of the stack array and nothing odd seems to happen.

At some unspecified time later, the corrupted stack contents may cause a crash, but only if you're lucky. If you're unlucky, someone pwns your computer via buffer overflow.)

nneonneo
  • 171,345
  • 36
  • 312
  • 383