Skip to content

Instantly share code, notes, and snippets.

@pgbovine
Created September 30, 2015 16:47
Show Gist options
  • Save pgbovine/8d9efefbfebd04d565ce to your computer and use it in GitHub Desktop.
Save pgbovine/8d9efefbfebd04d565ce to your computer and use it in GitHub Desktop.
#include <stdio.h>
void foo(int* x) {
printf("%d\n", x[3]);
}
int main() {
int arr[3];
int overflow = 1000;
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
foo(arr);
return 0;
}
@FranklinChen
Copy link

It's undefined behavior, so anything goes. You can't assume stack allocation or ordering or whatnot. On my Mac:

➜  ~  gcc -O0 foo.c
➜  ~  ./a.out
1000
➜  ~  gcc -O foo.c
➜  ~  ./a.out
32767
➜  ~  gcc -O6 foo.c
➜  ~  ./a.out
0

@jldugger
Copy link

Analyzing the results of gcc -O0 -masm=intel gistfile1.c should pretty much tell you what's going on, if you use it diagram out the stack frame of main.

On my Ubuntu desktop, int overflow = 1000; translates to mov DWORD PTR [rbp-36], 1000, and arr[2] = 30 translates into mov DWORD PTR [rbp-24], 30. arr[3] would be the contents of [rbp-20]. As Franklin points out, the allocation of stack ordering is not defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment