Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I would like to post on there but it's protected from people with low reputation... Maybe someone here appreciates my solution in C:

  #include <stdio.h>
  
  int main(int argc, char* argv[]){
  	int arr[1];
  	int a = 2;
  	int b = 2;
  	arr[1] = 3;
  	printf("%d", a+b);
  
  	return 0;
  }
Explanation: I go out of bounds of the array arr, it only has one value but I access the second value. That's why b is likely to get overwritten with 3 and hence a+b=5


I think the line above the printf call should be

    arr[2] = 3;
I ran your program and I got 4. Then I changed arr[1] to arr[2] and got 5, as I expected.


It's only likely, but not certain that a or b get overwritten. How your stack is laid out is entirely up to the compiler. arr[1] is already out of bounds, however, we don't know for certain what's immediately above the array.


With compiler optimizations turned on, it's almost guaranteed not to happen, because a and b are very likely to be stored in CPU registers.


Or rather, a and b will be constant folded so that the printf call is optimized to "push #4; push ptrFmt; call printf"


A truly good compiler would replace that printf by a call to putchar or pass a constant string to 'write' (gcc almost (?) does that. See http://www.ciselant.de/projects/gcc_printf/gcc_printf.html)


The compiler is probably aligning all stack elements to 8 bytes.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: