Pointers to Variables on Stack

Explore how the compiler places variables on the stack and find out how to exploit a simple vulnerability and hack an application.

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:

Press + to interact
#include <stdio.h>
int main()
{
int a = 5, b = 10;
int sum = 0;
int *ptr1 = &a, *ptr2 = &b;
int *ptrSum = &sum;
*ptrSum = *ptr1 + *ptr2;
printf("%d + %d = %d\n", *ptr1, *ptr2, *ptrSum);
return 0;
}

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