递增指针并分配新值 - 堆栈损坏

时间:2016-12-30 14:06:50

标签: c pointers

为了更好地演示我的问题,我编写了以下代码:

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'已经腐败了。"

1 个答案:

答案 0 :(得分:5)

*ptr = 2;   // dereferencing of ptr and store the value "2" in 0x01004

undefined behaviour。因为ptr这里没有指出地址,你可以合法地存储一些东西。 var只是一个 int,在ptr++;操作之后,无论它指向哪个地址,您都无法取消引用它。

如果varint的块,例如:

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] */