Question

I get a segmentation fault if i change the order of the arguments in a printf format string.

int main( int argc, char *argv[] )
{
    _uint64 test_var = 50000000;
    char str[20] = { };
    sprintf( str, "TEST_STRING" );

    printf( "test_var %lld str %s\n", test_var, str ); //OK
    printf( "str %s test_var %d\n", str, test_var ); //OK
    printf( "test_var %d str %s\n", test_var, str ); //Segmentation Fault

    return EXIT_SUCCESS;
}

Why am i getting this fault?

Was it helpful?

Solution

A 64-bit value is 64 bits (8 bytes). An int (which is what the format specifier "%d" uses) is 32 bits (4 bytes).

So what printf does in the crashing line is to read 4 bytes to print as an integer, then it will read the remaining four bytes (on a 32-bit system) or the remaining four bytes and the first four bytes of the string pointer (on a 64-bit system) to use as the string pointer. That string pointer is, as you can understand, not a valid pointer, and so you have undefined behavior which in your case leads to a crash.

OTHER TIPS

printf( "test_var %d str %s\n", test_var, str ); //Segmentation Fault
                  ^^

You should use %lld.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top