[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Bus error after casting (well defined) const unsigned char * to cons
From: |
Paul Pluzhnikov |
Subject: |
Re: Bus error after casting (well defined) const unsigned char * to const double * |
Date: |
Fri, 11 Aug 2006 15:14:47 -0700 |
User-agent: |
Gnus/5.1006 (Gnus v5.10.6) XEmacs/21.4 (Jumbo Shrimp, linux) |
"Earl Purple" <earlpurple@gmail.com> writes:
> So I receive the binary representation for a double (500000 in this
> particular case, which is 0x41 0x1e 0x84 0x80 0x00 0x00 0x00 0x00)
>
> If I reinterpret_cast the pointer to const double * then dereference it
> I get a Bus Error (core dumped).
The buffer into which you received the data must not have been
properly aligned.
> The workaround (that works) is to copy the buffer into a double, i.e.
> take a double, reinterpret_cast its address to unsigned char * and copy
> the buffer. That works, no crash.
You have to either do that, or ensure that the data is properly
aligned in the buffer. For example:
char buf[200];
receive_data(buf, sizeof(buf));
double *p = reinterpret_cast<double*>(buf); // BAD
double d = *p; // SIGBUS
do this instead:
union { char buf[200]; double d; } u;
receive_data(u.buf, sizeof(buf));
double *p = reinterpret_cast<double*>(u.buf); // OK
p = &u.d; // same thing
> It worked fine until I compiled in release mode with O3 optimisation
> setting.
So gcc decided to pack things differently on the stack, and your
buffer shifted its alignment. What else is new?
> Is this a known bug
Yes, in your program ...
> (as far as I'm aware it is not undefined behaviour)?
I am sure it *is*, but am too lazy to find the exact wording.
Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.