0
#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?

douyu
  • 2,377
  • 2
  • 14
  • 27
  • 2
    Undefined behavior is undefined. Sometimes it just appears to work. – Retired Ninja Oct 07 '22 at 13:01
  • 1
    Same reason as why some criminals are cought by police while others are not. Both are illegal but you cannot expect every fault being detected for you and presented to you on a silver tablet. – Gerhardh Oct 07 '22 at 13:29

1 Answers1

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273