简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM