删除void指针指向的内存

时间:2015-09-01 21:12:52

标签: c++ pointers struct delete-operator void-pointers

我正在函数中创建一个新的struct SThreadInfo

struct SThreadInfo {
    int             function;
    Exchange*       pThis;
};

struct SThreadInfo *threadInfo = new (struct SThreadInfo);
    threadInfo->function    = 0;
    threadInfo->pThis       = this;

然后,在同一个函数中,我创建一个新的线程,将结构传递给void-pointer:

pthread_t ret;
pthread_create(&ret, NULL, Exchange::staticThreadHelper, (void*)threadInfo);

在新线程中,我从void-pointer重构结构:

void* Exchange::staticThreadHelper(void* t)
{
    struct SThreadInfo* threadInfo = (struct SThreadInfo*)t;
    //....
    //....
}

在此功能结束时,我想删除tthreadInfo分配的内存。到目前为止,它适用于threadInfo,但不适用于t

delete threadInfo;
delete static_cast<struct SThreadInfo*>(t);

当我尝试将void-pointer强制转换回SThreadInfo时,会引发SIGABRT。 有人能告诉我如何正确地从空指针中删除内存吗?

2 个答案:

答案 0 :(得分:7)

The line:

struct SThreadInfo* threadInfo = (struct SThreadInfo*)t;

doesn't "rebuild" anything, it merely assigns a type casted value to the declared variable. It's the same pointer.

In the end of the function, you appear to be deleting (freeing) the same address twice, and that's why you get your exception.

答案 1 :(得分:2)

So, the problem here is that you have ONE lump of memory, that you have two different pointers to.

You should only free any allocated memory ONCE. If you have an object with a destructor [including ones that have implict destruction, e.g. something containing another object with a destructor, such as std::string or std::vector], you should make sure the delete call is made with the correct type.

So in this case, either delete static_cast<SthreadInfo*>(t); or delete threadinfo; should do the trick. Trying to delete the same memory more than once will lead to undefined behaviour [apparently your runtime library detects this and aborts the execution].