Search code examples
cgccglibc

Assigning uninitilialized void* pointer


#include <stdio.h>

void wat(void *ptr){
    *(int*)ptr = 0x4A424F4B;
    return;
}

int main(int argc, char **argv){
    FILE *wtf = fopen("wat", "wb");
    void *ptr;
    wat(ptr);
    return 0;
} 

This actually compiles and executes without errors, you can even fwrite contents of *(int*)ptr and you'll get 0x4A424F4B. However, when you remove this line:

FILE *wtf = fopen("wat", "wb");

*(int*)ptr = 0x4A424F4B; will suddenly cause a segmentation fault. Why?


Solution

  • Technically, your code has undefined behaviour.

    It happens to not blow up on your particular platform using your particular compiler because the uninitialized ptr happens to contain the address of some writable memory. Since we don't know where ptr is pointing, we can't know what harm the assignment is doing.

    Moving things around changes the addresses, and things "break" (strictly speaking, they weren't really working in the first place).