为了更好地演示我的问题,我编写了以下代码:
int *ptr;
int var;
var = 1; // lets assume that the lvalue of "var" is 0x01000
// which is a fictitious address, but needed for further explanation of my thoughts
ptr = &var; // so ptr points to 0x01000, where the 4 byte integer "1" is stored
ptr++; // pointer incrementing by 4 Bytes because we have a pointer of type integer
// pointer now points to 0x01004
*ptr = 2; // dereferencing of ptr and store the value "2" in 0x01004
// I expected somethink like:
// address| 00 01 02 03 04 05 06 07
// 0x1000 | 01 00 00 00 02 00 00 00 ....
// as the result of this code
我试着在评论中描述我对这段代码的想法,所以你可以更好地纠正我。
当我运行代码时,我得到了运行时错误"堆栈变量' var'已经腐败了。"
答案 0 :(得分:5)
此
*ptr = 2; // dereferencing of ptr and store the value "2" in 0x01004
是undefined behaviour。因为ptr
这里没有指出地址,你可以合法地存储一些东西。 var
只是一个 int
,在ptr++;
操作之后,无论它指向哪个地址,您都无法取消引用它。
如果var
是int
的块,例如:
int *ptr;
int var[5]; /* 5 int's */
var[0] = 1;
ptr = var; /* or, ptr = &var[0]; */
然后你可以增加并存储一些东西:
ptr++;
*ptr = 2; /* equivalent to assigning 2 to var[1] */