Shyam Prasanna
Shyam Prasanna

Reputation: 111

Accessing uninitialized memory in c

#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

Upvotes: 2

Views: 696

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223389

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.

Upvotes: 2

Related Questions