Why does the program print wrong value of shared object's global variable?

Viewed 190

I built a shared object from following C code with the following command :

gcc -fPIC -shared libx.c -o libx.so

libx.c

extern int printf(const char *, ...);

int libvar = 250;

void libfunc(){

    printf("%d,",libvar);    
}

Then i linked the following C code against the libx.so library with the following command:

gcc -no-pie -lx -L ./ -o main main.c

-no-pie : To tell the compiler to generate an ELF executable instead of a shared object (Because that's what my compiler does by default).

main.c

extern void libfunc();

int main(){
    libfunc();
}

Now, when launching the program, theoretically, the dynamic loader will map the shared library libx.so somewhere onto the address space of the running process (./main) and will resolve the symbols libfunc & libvar (Changing stuff in the .got and .plt segments for PIC), it will eventually resolve printf symbol and then print the value of libvar which is 250.
But the program prints some weird value:

root@afr0ck:~# ./main; printf "\n"
-1076465840

I've been debugging for longtime to understand what's going on but i can't figure it out !

3 Answers
Related