[英]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 Output:垃圾值
#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 Output:运行时错误
In both the programs k is a pointer variable and it access the uninitailzed memory.在这两个程序中,k 都是一个指针变量,它访问未初始化的 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
.在第一个示例中, k++
在i
之后递增k
以指向 memory 。 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.虽然访问此 memory 不是由 C 定义的,但在常见的实现中(特别是在编译器的优化没有显着改变代码的情况下), i
存储在堆栈中。 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.该堆栈也用于其他用途,因此在i
之前和之后还有其他可访问的 memory ,并且使用*k
可能会从此 memory 获取数据。
In the second example, k++
increments k
to point to the memory after j
.在第二个示例中, k++
递增k
以指向j
之后的 memory 。 Then *j
may fetch data from this memory, as with the first example.然后*j
可以从这个 memory 中获取数据,与第一个示例一样。 Then **j
may use that data as a pointer to access other memory.然后**j
可以使用该数据作为访问其他 memory 的指针。 But the contents of *j
are not generally a meaningful address.但*j
的内容一般不是有意义的地址。 Quite likely, they form an address that is not mapped in the virtual memory space of your process.很可能,它们形成的地址未映射到进程的虚拟 memory 空间中。 Attempting to access that address results in the hardware generating a fault.尝试访问该地址会导致硬件产生故障。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.