pointer arithmetics and runtime error

I am using the following code to learn how pointer works. It complies and can print out results, but also gives me a runtime error: Stack around variable myvar is corrupted. What does that mean and why does it happen? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  Put the code you need help with here.#include <iostream>
#include <utility>

using namespace std;

int main()
{
	int myvar = 4;
	int * foo = &myvar; 
	int * goo = ++foo; 
	*goo = 5; 
	int *hoo = goo + 1;
	*hoo = 6;

	cout << foo << endl; //0093FEB8
	cout << *foo << endl; //5
	cout << *++foo << endl; //6
	cout << *goo << endl; //5
	cout << foo << endl; //0093FEBC

	cin.get();
}
Let's walk through it.

Line 8: You start with allocating space for myvar.
Line 9: Then, the foo pointer points to myvar. Okay, nothing bad so far.

Line 10: Next, you increment the foo pointer to the next address, and assign that value to goo (still just a pointer). goo now points to an invalid memory location, but this okay for now, because you haven't dereferenced the goo pointer.

Line 11: The problem comes when you now try to dereference goo, on line 11. goo is not pointing to a valid memory location, because you incremented it past the original address of mvar.

Line 13: Then you also try to dereference hoo, which is in an address that is past goo, also invalid.

Your program has undefined behavior because you're accessing invalid memory addresses.

If you want to access adjacent memory addresses, use arrays.
Last edited on
Thank you. In line 10, I assigned goo to point to the next memory address of foo. Why is that memory address invalid? Is it because I must declare the memory I want to use at compile time? It's probably related to some basic memory management knowledge I wasn't aware of.
Why is that memory address invalid? Is it because I must declare the memory I want to use at compile time?

Yes. You can't try to use memory that you haven't told the compiler is supposed to be allocated for your use. The compiler could have decided to use that memory for anything; it has control over that memory, not you, and writing into it could be overwriting something else that you're not aware of. This is what we call undefined behaviour.
Topic archived. No new replies allowed.