Search code examples
cstack

Why access out of bound memory fun(4) / fun(5) can output and fun(6) is stack smashing detected?


#include <stdio.h>

typedef struct {
  int a[2];
  double d;
} struct_t;

double fun(int i) {
  volatile struct_t s;
  s.d = 3.14;
  s.a[i] = 1073741824; /* Possibly out of bounds */
  return s.d;
}

int main(void) {
  int size = 6;
  for (int i = 0; i <= size; i++)
    printf("%.10lf\n", fun(i));
  return 0;
}

3.1400000000
3.1400000000
3.1399998665
2.0000006104
3.1400000000
3.1400000000
*** stack smashing detected ***: terminated
Aborted

In x86-64, the size of struct_t is 16, so why fun(4) and fun(5) can output that exceed struct size?


Solution

  • When you write past the bounds of an array, you trigger undefined behavior.

    This basically means that no guarantees can be made regarding what your program will do. It might crash, it might output strange results, or it might appear to work properly. Additionally, making a seemingly unrelated change, such as adding a call to printf for debugging or adding an unused local variable, can change the way undefined behavior manifests.

    Just because your program could crash doesn't mean it will.