Search code examples
cprintinginfinite

Why this function causes non-stop printing?


Hello a friend of mine shown me this piece of code to make a point about array/stack bound checking.

#include <stdio.h>

void foo() {
    unsigned long long a[1];
    a[3] -= 5;
    printf("Print me!\n");    
}

int main(){ 
    foo();
    return 0;    
}

When I run this code, it keeps printing "Print me!\n" all the time, it just doesn't stop. I've compiled code with MingW 64bit. What's happening here? I'd like someone to explain me, why it keeps printing the text.


Solution

  • You damage thread stack by command a[3] -= 5; because changing var out of array range. The behavior is totaly unpredictable and can be different on other systems. I think you just modify return address on stack to call printf

    If you want to understand - use disassembler.