开发者

Weird error casting an LPVOID to an int pointer

I get this weird error:

MyView:OnInitialUpdate()
{
    int* my_int;
    *(my_int) = 1;
    AfxBeginThread(MyThread,my_int);
}

UINT MyThread(LPVOID param)
{  
    int* my_int = reinterpret_cast<int*>(param);
    message(*(my_int));
        return 0;
}

void message(int value)
{
    CString txt;
    txt.Format(_T("%d"),value);
    AfxMessageBox(txt);
}

The message box output i开发者_开发问答s 4250636.

Now if I just add another message box before passing the value to the thread:

MyView:OnInitialUpdate()
{
    int* my_int;
    *(my_int) = 1;
    message(*(my_int));
    AfxBeginThread(MyThread,my_int);
}

Both message box outputs are 1.


int* my_int;
*(my_int) = 1;

This is undefined behavior. You didn't initialize my_int, so you're dereferencing an invalid pointer.

Instead, create a member x in your MyView class, and change to:

int* my_int = &x;


This

int* my_int;

defines a pointer to some integer without initializing it with an actual integer's address, so it points at some random address in memory.
This

*(my_int) = 1;

then writes a value to this random address.

Officially, this invokes the dreaded Undefined Behavior. After that, all bets are off. Even if your computer would explode into your face as a result of that, your compiler would be standard-conforming.


However, there's more to this: Since you pass that pointer to some function which is to be executed asynchronously, you need to make sure that the object the pointer refers to is "alive" for as long as your other thread will try to access it. Basically, the only ways to do that would be to make it global, static, or dynamically allocated.
However, given your code I see no reason you need to pass an actual pointer anyway. Passing reinterpret_cast<LPVOID>(1) should do.


The above both correct but another way of saying it:

*(my_int) = 1

means: set what my_int points to 1 - but my_int is not yet pointing to anything - boom.


You can use

AfxBeginThread(..., reinterpret_cast<LPVOID>(static_cast<INT_PTR>(input)));

and inside your thread function

int my_int = static_cast<int>(reinterpret_cast<INT_PTR>(rawInput));

This also works with enums instead of int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜