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



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

以下代码是原始作品的模型。它在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;
}

如果您有任何意见或想法,谢谢!

问题出在

(unsigned long) 

适用于 32 位的强制转换。 用

(unsigned long long)

相反。您需要到处进行更换。

否则,请摆脱 int 到指针的转换或使用 32 位编译器

最新更新