0

I came across this question when I was reading about vulnerable C programs involving strtol. Below is the code

#include <stdio.h>
void f (int i, int j) {
    int a[50];
    a[i] += j;
}
int main (int argc, char *argv[]) {
    int x = 10, y, z;
    if (argc > 1) {
        y = strtol (argv[1], NULL, 10);
        z = strtol (argv[2], NULL, 10);
        f(y, z);
        x = 20;
        printf ("x=%d\n", x);
    }
    return 0;
}

The call strtol(s, NULL, 10) returns the integer written as string s in decimal notation. What inputs should one be giving to print x value as 10 and what is the idea behind giving those inputs?

ekad
  • 14,436
  • 26
  • 44
  • 46
  • 1
    To retain the initial value of `x==10` you need to skip `x = 20;` assignment, so you'll have to modify the return address on the stack. The position of the return address relative to the local `a[]` variable, measured in `sizeof(int)` units, which is a desired `i` parameter value, strongly depends on a compiler, destination machine and optimization modes. The value you need to add (the `j` value) in turn is the length of the instruction to skip which also depends as above. – CiaPan Sep 15 '16 at 15:31
  • Tried it. Got it. Thanks :) – Rajiv Reddy Sep 17 '16 at 10:35

0 Answers0