dunecat
dunecat

Reputation: 140

Pointer Dereferencing = Program Crash

unsigned int *pMessageLength, MessageLength;
char *pszParsePos;

...
//DATA into pszParsePos
...

printf("\nMessage Length\nb1: %d\nb2: %d\nb3: %d\nb4: %d\n",
    pszParsePos[1],pszParsePos[2],pszParsePos[3],pszParsePos[4]);

pMessageLength= (unsigned int *)&pszParsePos[1];

MessageLength = *((unsigned int *)&pszParsePos[1]);

//Program Dies

Output:

Message Length
b1: 0
b2: 0
b3: 0
b4: 1

I'm don't understand why this is crashing my program. Could someone explain it, or at least suggest an alternative method that won't crash?

Thanks for your time!

Upvotes: 3

Views: 894

Answers (2)

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19467

Here's what I think is going wrong:

You added in a comment that you are runing on the Blackfin Processor. I looked this up on some web sites and they claim that the Blackfin requires what are called aligned accesses. That is, if you are reading or writing a 32-bit value to/from memory, then the physical address must be a an even multiple of 4 bytes.

Arrays in C are indexed beginning with [0], not [1]. A 4-byte array of char ends with element [3].

In your code, you have a 4-byte array of char which:

  • You treat as though it began at index 1.
  • You convert via pointer casts to a DWORD via 32-bit memory fetch.

I suspect your 4-char array is aligned to a 4-byte boundary, but as you are beginning your memory access at position +1 byte, you get a misalignment of data bus error.

Upvotes: 2

JaakkoK
JaakkoK

Reputation: 8387

Bus error means that you're trying to access data with incorrect alignment. Specifically, it seems like the processor requires int to be aligned more strictly than just anywhere, and if your *pszParsePos is aligned, say on an int boundary (which depends on how you initialize it, but will happen, e.g., if you use malloc), it's certain that &pszParsePos[1] isn't.

One way to fix this would be constructing MessageLength explicitly, i.e., something like

MessageLength = (pszParsePos[1] << 24) | (pszParsePos[2] << 16) | (pszParsePos[3] << 8) | pszParsePos[4]

(or the other way around if it's supposed to be little-endian). If you really want to type-pun, make sure that the pointer you're accessing is properly aligned.

Upvotes: 3

Related Questions