funwithlinx
funwithlinx

Reputation: 39

C++ Stack around the variable x was corrupted

I am new to C++. I am learning some basics. I tried the below program and got a run time error Stack around the variable x was corrupted.

int x = 56;
int *ptr = &x;
ptr[1]=8;
cout << *ptr << endl;

But if i update the index in line 3 to 0, say ptr[0] = 8, I am not getting any run time error and the console shows 8 as the output.

I assume 2 digits in the integer variable x and thought pointer index will have 0 and 1 as valid values. Why ptr[1] is causing run tume error where as ptr[2], ptr[3] does not cause any run times error and simply shows 56 as o/p.

Can any one help me to understand what is really going on here. May be a better tutorial site as an add on would help me to understand more on this subject.

Upvotes: 0

Views: 1564

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

Presumably you were expecting ptr[1] to mean the second byte in x. But that's not how pointer arithmetic works. The pointer is an int*, so arithmetic is performed in "chunks" of int-sizes. Therefore, ptr[1] is the non-existent integer "next to" x.

You could probably see this working by making ptr a char* instead, but be careful because this is real hackery and probably not a good idea unless you really know what you're doing.

A further misconception is your indication that the number of decimal digits in the human-readable representation of x's value has anything to do with the number of bytes taking up by x in memory; it doesn't.

Upvotes: 1

Arunmu
Arunmu

Reputation: 6901

Let see what you are doing here (Lets assume int is 4 bytes):

int x = 56;
int *ptr = &x;
ptr[1]=8;
cout << *ptr << endl;
<- 4 bytes->......(rest of the stack)
 ----------------
|   x     |      |
 ----------------
^         ^
ptr[0]   ptr[1]

So, pre[1] is writing to a memory location which does not yet exist. So, you are writing data out-of-bound.

Upvotes: 1

Paul Stelian
Paul Stelian

Reputation: 1379

ptr[1] is actually the integer next to the variable pointed to by ptr. Writing to such memory means overwriting about anything. You may overwrite other variables. Or return addresses. Or stack frames. Or about anything else. Heck, you may overwrite ptr itself, depending on how variables on the stack are arranged.

Undefined behavior. Compilers are allowed to assume it doesn't happen.

Upvotes: 3

Related Questions