cdonts
cdonts

Reputation: 9599

Struct attribute changed after usage

In the following example, once we access the bar attribute its value automatically changes.

typedef struct {
    DWORD bar;
} MYTYPE;

void Create(LPVOID *myTypePtr)
{
    MYTYPE myType;
    myType.bar = 50;
    *myTypePtr = &myType;
}

int _tmain(int argc, _TCHAR* argv[])
{
    DWORD foo;
    MYTYPE *fooPtr;

    Create((LPVOID)&foo);
    fooPtr = (MYTYPE*)foo;

    printf("%d\n", fooPtr->bar);  // This prints 50 (ok).
    printf("%d\n", fooPtr->bar);  // This prints 2147344384 (garbage).

    return 0;
}

Yes, the structure must be passed as a void pointer. I'm probably missing some conversion detail but I can't get it. Compiling with Visual C++ 2003.

Any ideas?

Upvotes: 0

Views: 107

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

In the function Create, you are making the argument myTypePtr point to a local automatic variable myType. The variable myType is out of scope when the function exits, so it's undefined behavior to dereference the pointer that points to it after the function exits.

Upvotes: 1

Related Questions