2

I'm actually porting a Linux app to Mac OS X. My problem is that I can access the variables but not the pointers.

I declared the variables in the main.h this way:

uint64_t test;
uint64_t *test2;

In the mylib.h:

extern uint64_t test;
extern uint64_t *test2;

and in mylib.c I access the variables this way:

printf("%llu\n",test);
printf("%llu\n",*test2);

The first printf() doesn't have any problems but the second gives me this error:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008

Does anybody know why this happened?

My ggc command line has the following flags:

gcc -Wall -g -fPIC -c main.c gcc -shared -Wl,-undefined,dynamic_lookup -o mylib.so mylib.o
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Neo
  • 149
  • 5
  • Has test2 been assigned a valid pointer? – Mark Wilkins Dec 03 '12 at 16:45
  • That's a curious command line. Are you producing a program called `mylib.so`? And since you're linking `main.o` (indirectly; you specify `main.c` on the command line) and `mylib.o` on the command line, what are you using `dlopen()` on? – Jonathan Leffler Dec 03 '12 at 17:13
  • @JonathanLeffler: There's a `-shared` in there, which ends up generating a shared library on Mac OS X. –  Dec 03 '12 at 17:38
  • @duskwuff: OK; so do we have to assume, then, that `main.c` does not actually contain a `main()` function instead? Or is this a shared library with a `main()` in it? I'm still a little puzzled by the scenario. We haven't seen the `dlopen()` and `dlsym()` code... – Jonathan Leffler Dec 03 '12 at 18:47
  • @JonathanLeffler of course the main.c contains a main() but i'm sure there isn't a problem with `dlopen()` and `dlsym()` because i can access other elements of `mylib.so` without problems only the pointers (in this case test2) make problems. – Neo Dec 04 '12 at 09:26

1 Answers1

0

Just for someone with a similar problem:

I decided to work with getter & setter because there wasn't problems to access the function of the main program with a dynamic library just the variables.

in mylib.c :

test2 = getTest();

in main.c :

uint64_t* getTest(){
    return &test;
}

Update

I finally found a way around this getter & setter. The problem you are facing is that you're defining your variable twice, in my case this happened during a misunderstanding of the extern keyword. To solve your problem you need to declare the variables as extern in your main.h e.g.:

extern uint64_t test;
extern uint64_t *test2;

Next step is to define the variables in your main.c e.g.:

int main(...) {
    test = 1;
    test2 = &test;
}

And finally remove the extern declaration from your mylib.h

The following SO post led to my solution: link

Community
  • 1
  • 1
Neo
  • 149
  • 5