Is there any way a C/C++ program can crash before main()?

With gcc, you can tag a function with the constructor attribute (which causes the function to be run before main). In the following function, premain will be called before main:

#include <stdio.h>

void premain() __attribute__ ((constructor));

void premain()
{
    fputs("premain\n", stdout);
}

int main()
{
    fputs("main\n", stdout);
    return 0;
}

So, if there is a crashing bug in premain you will crash before main.

Leave a Comment