C Member value lost when passing object by pointer

I am very new to the FreeBSD world and am currently porting my terminal emulation library from Linux to FreeBSD and Mac OS. I've encountered some very strange behavior that I've not seen before. Basically, I have some code that does this:

C:
void routineA(obj *myobject)
{
    printf("%d", myobject->x);
    routineB(myobject);
}

void routineB(obj *myobject)
{
    printf("%d", myobject->x);
}

When I inspect the value of 'x' in routineA() it will be a positive number (as it should be). However, the value of 'x' in routineB() is always zero. This does not happen when I build the code on Linux or Mac OS. It also does not matter whether I compile with gcc or clang on FreeBSD. I've exhausted all of the my normal debugging procedures and am considering some more obscure possibilities like stack smashing. However, when I look at ulimit the stack size is set to 524288 and on Linux it is 8192 (so that seems an unlikely culprit). Has anyone encountered something like this on FreeBSD. I'm using FreeBSD version 12.0 fwiw.
 
You are doing something incorrect, but without the code it's impossible to guess.

Here's a working example of what I think you want to do:

Code:
#include <stdio.h>

class obj {
public:
 int x;
};

void routineB(obj *myobject)
{
    printf("%d", myobject->x);
}

void routineA(obj *myobject)
{
    printf("%d", myobject->x);
    routineB(myobject);
}

int main() {
 obj o;
 o.x = 25;
 routineA(&o);
}

And the output:
Code:
$ ./a.out
2525$
 
It sounds like memory corruption or another form of undefined behaviour.

FreeBSD has Valgrind support (a decent memory debugger). Perhaps run your program through that and see if it can yield any useful info.
 
To get a little more feedback for yourself, change the printf to ...

Code:
printf("%p - %d\n", obj, obj->x);

Are the function prototypes declared in header files? Do the signatures match? Are you mixing "C" and C++?
 
Are you 100% sure all the routines here are talking about the same object? With modern C++, it might be that the object was copied, and some of them are looking at a copy.

Concrete suggestion: Print out the address of the object in all affected places:
printf("In routine A, myobject is at %p, and x is at %p.\n", (void*) obj, (void*) &(obj->x));

EDIT: Unitrunker beat me by one minute.
 
Back
Top