vendredi 29 mai 2015

Interesting GCC Linking

I was playing around with symbols and function pointers recently and noticed that though the following code runs fine:

#include <stdio.h>
int main(int argc, const char * argv[]) {
    printf("%p\n",printf); // <--this line makes it work
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}

This does not:

#include <stdio.h>
int main(int argc, const char * argv[]) {
    // printf("%p\n",printf); // <-- commenting this out breaks it
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}

(EXC_BAD_ACCESS)

How come dereferencing the exact same pointer causes issues when there is no reference to printf in the code? Even this works fine:

#include <stdio.h>    
int main(int argc, const char * argv[]) {
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}
void *_ = printf; // <-- because of this

Why is this?

Aucun commentaire:

Enregistrer un commentaire