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.
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.
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.