Pointers to Variables on Stack
Explore how pointers to local variables are stored on the stack in C programming. Understand variable address ordering, stack memory layout, and the dangers of out-of-bounds indexing that can lead to overwriting adjacent variables. Learn through examples the importance of careful memory management and how improper input handling can cause security vulnerabilities.
We'll cover the following...
Creating pointers recap
In the first chapter, we created pointers to variables and used them to change or read the values in those variables. The variables get placed on the stack, so we already had the first taste. But, to refresh our knowledge, let’s write one more example:
Here, ptr1 points to a, ptr2 to b, and ptrSum to sum.
Then, *ptr1 gives the value of a and *ptr2 gives the value of b. Added together, *ptr1 + *ptr2 gives the sum of a and b. To write that to sum, we use *ptrSum.
If you were to point that out, the code could be:
int sum = a + b;
You would be correct!
We are still at a stage where we must resort to these basic examples to get the hang of pointers. In the next section, we will start solving some real problems, not just dummy examples.
Now we know that a, b, sum, ptr1, ptr2, and ptrSum are local variables of main.
Therefore, they are all placed on the stack. Yes, even the pointers. They work as regular variables in ...