简体   繁体   English

强制转换指针时崩溃-C

[英]Crash while typecasting a pointer - C

C-Beginner Question: 初学者问题:

I have the following code that crashes at line unsigned long rdwValue = *((unsigned long*)pParamPtr); 我有以下代码在unsigned long rdwValue = *((unsigned long*)pParamPtr); . I am cross compiling the code for a MIPS32 target on a fedora machine using GCC 我正在使用GCC在fedora机器上交叉编译MIPS32目标的代码

unsigned char* pParamPtr = GetNvParamRamAddress(ParameterId, swIndex);

if (0 != pParamPtr)
{
    unsigned long rdwValue = *((unsigned long*)pParamPtr);// CRASHES
}

But if I change the line inside the if to 但是如果我将if内的行更改为

rdwValue = *(pParamPtr);

this works. 这可行。

Am I doing something against the rules with this typecasting? 我使用这种类型转换是否违反规则?

What I need is to get a four bytes [unsigned long is 4 bytes] from address starting at pParamPtr into rdwValue. 我需要的是从pParamPtr到rdwValue的地址获取四个字节[无符号长为4个字节]。

Is it memcpy the way to go? 它是memcpy的路吗?

What platform is this running on? 它在什么平台上运行?

One likely reason is alignment restrictions being violated, if the returned pointer is odd and the platform doesn' support reading unsigned long s from odd addresses this would fail. 一个可能的原因是违反了对齐限制,如果返回的指针为奇数,并且平台不支持从奇数地址读取unsigned long ,则此操作将失败。

UPDATE According to a comment the OP is running this on MIPS, which certainly has alignment restrictions. 更新根据评论,OP在MIPS上运行此程序,它当然具有对齐限制。

As a minor stylistic point, your outer pair of parenthesis aren't needed, it could be just: 作为次要的风格问题,不需要您的外部括号,这可能只是:

unsigned long rdwValue = *(unsigned long *) pParamPtr;

It might be easiest to read the bytes one by one, that also gives you a chance to handle endianness explicitly. 可能最容易地一一读取字节,这也使您有机会显式地处理字节序。 Assuming little-endian (and at least 32-bits of int precision): 假设使用低位字节序(至少32位的int精度):

unsigned long rwdValue = pParamPtr[0] | (pParamPtr[1] << 8) | (pParamPtr[2] << 16) | (pParamPtr[3] << 24);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM