I’m writing some code in pure C, RHEL 5.5 x64, gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)
I’ve got an executable which is compiled using 2 static libraries. Each of them uses some global (for a given library) array variables (i.e. in some .c file I have a
char var1[VAR_SIZE1];, then in other .c files of the lib I use extern char var1[VAR_SIZE1];, and the same situation with the second lib).
Each library is placed in it’s own subdir of an executable source dir.
I’ve started to notice that one lib can place its data in another lib’s memory. To discover what’s going on, I’ve defined a void pointer to one of the variables in a third lib, (lib 3 is used by both libs in question), assigned this pointer an address in lib1 and looked at the addresses in lib2.
What I see now is:
char var1[1000]; /*please mind the length*/
extern void* ptr_to_var2;
printf("var1 addr is %p, var2 addr is %p\n", (void*)&var1, ptr_to_var2);
this code produces
var1 addr is 0xa11b00, var2 addr is 0xa11e00
As you can see, var1 should end up at address 0xa11ee8, and var2’s head is INSIDE var1 memory.
What am I doing wrong? Are there any limitations on using global vars in static libs? I can’t define those vars as static, as they are used throughout a number of files inside each lib, and making those vars dynamic is a big work (there are dozens of such variables).
P.S. Of course, ptr_to_var2 is initialized. What really is going on
<lib3>
void* ptr_to_var2;
<lib2>
#include "hdr_with_my_struct_name_definition.h"
my_struct_name var2[5];
extern void* ptr_to_var2;
int func2(){
ptr_to_var2=(void*)&var2;
var2[0].fld1=12345;
return 1;
}
<lib 1>
#include "hdr_with_my_struct_name_definition.h"
char var1[1000];
extern void* ptr_to_var2;
int func1(){
my_struct_name *temp_var_2=(my_struct_name*)ptr_to_var2;
printf("%d", temp_var_2[0].fld1);
memset(var1, '\0', sizeof(var1);
printf("%d", temp_var_2[0].fld1);
return 1;
}
<binary>
main(){
func2();
func1();
return;
}
All of this returns
12345
0
In this, you are trying to print value of
ptr_to_var2not actually the address of it. As this variable is not initialized yet, its value is random as can be anything.gives: