2
#include<stdio.h>
int main(){
    int i = 3;
    int *k;
    k = &i;
    k++;
    printf("%d ",*k);
    return 0;
}

Output : Garbage value

#include<stdio.h>
int main(){
   int i = 3;
   int *j;
   int **k;
   j = &i;
   k = &j;
   k++;
   printf("%d ",**k);
   return 0;
}

Output:Runtime error

In both the programs k is a pointer variable and it access the uninitailzed memory. My Question is why it returns as runtime error in the second program

  • 5
    It's undefined behavior. You get what you get. – Fred Larson Dec 08 '21 at 14:08
  • 2
    While it's all undefined behavior, dereferencing a garbage pointer is more likely to cause some sort of runtime error than deferencing an off-by-one pointer. In the second one `*k` is a garbage pointer value, so `**k` dereferences a garbage pointer. – Paul Hankin Dec 08 '21 at 14:09
  • [What is undefined behavior and how does it work?](https://software.codidact.com/posts/277486) – Lundin Dec 08 '21 at 14:19

1 Answers1

2

In the first example, k++ increments k to point to the memory after i. While accessing this memory is not defined by C, in common implementations (and particularly where optimization by the compiler has not significantly changed the code), i is stored on the stack. The stack is used for other things as well, so there is other accessible memory before and after i, and using *k may fetch data from this memory.

In the second example, k++ increments k to point to the memory after j. Then *j may fetch data from this memory, as with the first example. Then **j may use that data as a pointer to access other memory. But the contents of *j are not generally a meaningful address. Quite likely, they form an address that is not mapped in the virtual memory space of your process. Attempting to access that address results in the hardware generating a fault.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312