简体   繁体   中英

Crash while typecasting a pointer - C

C-Beginner Question:

I have the following code that crashes at line unsigned long rdwValue = *((unsigned long*)pParamPtr); . I am cross compiling the code for a MIPS32 target on a fedora machine using GCC

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

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.

Is it memcpy the way to go?

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.

UPDATE According to a comment the OP is running this on MIPS, which certainly has alignment restrictions.

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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