We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Pointers to the Stack

So we know that stack frames are always getting pushed and popped, and as a result, memory addresses on the stack are always changing and getting reused.

Remember: the stack is only safe to use within the context of the current function!

Assignment

Let's get back to Sneklang's built in 2D graphics library. Take a look at the new_coord function. It accepts an x and y value and creates a new pointer to a stack-allocated coord_t struct.

  1. Because we're accessing stack memory (the pointer created on line 16) outside of the function that created it, the memory has been deallocated and is no longer safe to use. Technically the behavior is undefined, but it's likely that in this specific scenario you're just seeing it get overwritten by the next function call (thus 50 and 60 always print).