Search code examples
cpointerstermination

What's wrong with this code which prints the value at address obtained after converting an integer to an integer pointer


#include<stdio.h>

int main()
{
    int a = 10;
    int* p = &a;
    int** q = &p;
    printf("\n%d %d %d", a, *p, **q);

    int y = (int*)2000;
    printf("%d", y);

    /*
    printf("\n%d %d %d %d", a, *p, **q, *((int*)2000)); //Error line.
    */

    return 0;
}

This code compiles and runs. However, if you uncomment the commented code, the code still compiles but terminates before printing the result of the last printf command.

My 2 questions are:

  1. If *((int*)2000) is a perfectly valid code like (int*)2000 (i.e., an integer turned into an address/pointer to get the value at that address), why does program stop before the end if *((int*)2000) is present?
  2. Why doesn't this code print the values of a, *p, and **q before terminating the program (they are printed before trying to print *((int*)2000))) ?

Solution

    1. *((int*)2000) is not "perfectly valid code". The result of converting an integer to a pointer is implementation-defined. It's likely that in your implementation, (int*)2000 results in an invalid pointer. Trying to dereference an invalid pointer produces undefined behavior, which means that anything can happen. When you ran the program with the printf line uncommented, it happened to result in a segmentation violation, because the resulting pointer pointed to unaccessible memory. If you'd used some other integer, it might have resulted in a valid pointer, and then you'd see the contents of that memory location.

    2. All the parameters to a function call have to be evaluated before the function is called. The above error is happening while evaluating the parameters to printf(), so the program stops before the function is called. As a result, nothing is printed.