C指针转换导致内存访问冲突

时间:2018-06-20 10:34:03

标签: c++ qt pointers

我正尝试使用Microsoft MSVC 2015 64位编译器将旧项目从Borland BCC 5迁移到Qt 5.6.3。

以下代码是原始作品的模型。它可以在Visual Studio 2015和Borland BCC 5中按预期工作,但是,当我尝试使用Qt Creator 3.6.1在Qt 5.6.3中运行它时。由于无法访问“ * hcID”,因此会引发错误。

#include <stdlib.h>

typedef void (*ProcFoo)  (void *pvData, unsigned long ulBarTag);

static char* gpcID = NULL;

typedef struct FooType
{
    ProcFoo       pfFoo;      ///< pointer to Foo callback function
    unsigned long ulBarTag;   ///< base id
} FooType;

FooType* pFoo = NULL;

void RegisterAsFoo(unsigned long ulBarTag, ProcFoo pfFoo)
{
    pFoo = (FooType*)malloc(sizeof(FooType));

    pFoo->ulBarTag = ulBarTag;
    pFoo->pfFoo = pfFoo;
}


void GetBarTag(unsigned long *pulBarTag, unsigned long ulBarTag)
{
    *pulBarTag = ulBarTag;
}


int main()
{
    char s[] = "Some Value";
    gpcID = s;
    char ** hcID = NULL;

    RegisterAsFoo((unsigned long)&gpcID, (ProcFoo)GetBarTag);

    pFoo->pfFoo(&hcID, pFoo->ulBarTag);


    // after the execution, the hcID is still NULL in Qt 5.6.3, however, 
    // it is valid in Visual Studio 2015 and Borland BCC 5.
    char* result = (*hcID);

    return 1;
}

感谢您有任何意见或想法!

1 个答案:

答案 0 :(得分:-1)

问题出在

(unsigned long) 

cast适用于32位。 使用

(unsigned long long)

相反。您需要在整个地方进行替换。

否则,请放弃将int转换为指针的方法,或者改用32位编译器