0

I have code that looks like this :

Foo* create(args) {
    Foo *t = malloc (sizeof (Foo)) ;
    // Fill up fields in struct t from args. 
    return t;
} 

The call is

Foo *created = create (args) 

Note that the function and the call to the function are two separate modules. The value of the pointer assigned to t on being malloced is slightly different to what is captured in created. Seemingly the MSB of the address is changed and replaced with fffff. The LSB portion is the same for around 6-7 characters.

I'm at a loss as to what's going on. I'm using GCC 4.6

WedaPashi
  • 3,561
  • 26
  • 42
user2624119
  • 107
  • 2
  • 11
  • 3
    Can you please include all relevant code, specifically the code you are using to print the pointer, both in create and out of it. – missimer Jul 07 '15 at 02:04
  • Likely to be 32/64 bit issue. Possibly same or similar issue to this: https://stackoverflow.com/questions/31094133/memccpy-return-lower-memory-address-than-the-src-starting-address#comment50204886_31094133. But we can't tell just from the info you have provided. – kaylum Jul 07 '15 at 02:12
  • 2
    Do you see any warnings when you compile with the -Wall flag? – Abednego Jul 07 '15 at 02:18

1 Answers1

7

The most likely explanation one can come up with from what you provided is that at the point of the call the function create is undeclared. A permissive C compiler assumed that unknown function create returned an int and generated code, which effectively truncated the pointer value or, more precisely, sign-extended the assumed int return value into the MSB of the recipient pointer (assuming a platform where pointers are wider than int in terms of their bit-width, e.g. 64-bit platform).

Most likely the compiler issued a warning about an undeclared function being called, but the warning was ignored by the user.

Make sure declaration (or, better, prototype) of create is visible at the point of the call. If you are compiling in C99 mode (or later), ask your compiler to strictly enforce C99 requirements. And don't ignore compiler diagnostic messages.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • That diagnosis was super accurate. This is EXACTLY what happened. The build system prints out so much stuff on screen, I missed the warning for implicit declaration. – user2624119 Jul 07 '15 at 19:36