Answers ( 4 )

  1. 2017-01-03 10:01

    Because accessing the uninitialized pointer A[2] invokes undefined behavior, which means anything is allowed to happen as far as the C standard is concerned.

    why there is no compile time error

    Because the standard doesn't require a diagnostic (such as a compile error) to be issued in this case.

  2. 2017-01-03 10:01

    This statement gives no compile time error in c

    Because there is no syntactical error or constraint violation that compiler should be judging. C does not do any bound-checking for arrays (or pointer arithmetics).

    You'll be perfectly allowed to write a code which makes use of invalid memory (example: dereference an invalid memory location) but in case, the compiler has produced a binary for such code, running the binary would invoke UB.

    yet when i run the program it gives a runtime error

    In your code,

      int *A [10];

    A is an array of 10 int *s, and they are not initialized explicitly. Looking from the snippet, it appears A is not in global scope, i.e., not having static storage, so the contents of each of those pointers are indeterminate.

    So, later in process of writing A[2][3]=15;, you're trying to access A[2] (a pointer), which points to an invalid memory. This invokes undefined behavior.

  3. 2017-01-03 11:01

    It's for the same reason that

    int a, d = 0;
    a = 1 / d;

    compiles cleanly. To detect the invalid operation the compiler would need to run the program.

  4. 2017-01-03 12:01

    Your compiler doesn't perform deep enough static analysis to detect the error at compile time. If you want better automatic detection of such errors then try tools like splint from or PC-Lint/FlexeLint from . These tools have not caught up with the latest C standards, so they do not support some of the newer features. Both of these will automatically detect your problem, Splint says

    Array element A[2] used before definition An rvalue is used that may not be initialized to a value on some execution path. (Use -usedef to inhibit warning)

    PC-Lint/FlexeLint (through the interactive try-before-you-buy page) says

    Warning 530: Symbol 'A' (line 2) not initialized

    and warning 530 is further explained as

    Symbol 'Symbol' (Location) not initialized -- An auto variable was used before it was initialized.

    Such tools can help you to learn, and provide a useful safety net. In the long run it is more satisfying to be able to reason about programs in your own mind.

◀ Go back