Unhandled exception at XXX. Datatype misalignment.

Started by
3 comments, last by hplus0603 16 years, 11 months ago
Iv run into some problems. Im sending packets using sockets. Before i send em, i batch em togethere in a large buffer to keep packet count down. However, when i try to unpack the batch on the receiver side, i get an excepthin thrown "Datatype misalignment.". This happens when using the =(assignment) operator in my matrix classes for its float members. memcpy'ing the entire matrix instead works fine. But i feel there is a problem here that i want to get to the bottom with. MSDN states: STATUS_DATATYPE_MISALIGNMENT Reading or writing to data at an address that is not properly aligned; for example, 16-bit entities must be aligned on 2-byte boundaries. (Not applicable to Intel 80x86 processors.) However i still dont understand why this happens, im not using any pragma pack's in the code, so everything should be aligned nicely right? What im doing is this: char* buffer = socket.recv(); my_packet_type_t* packet = (my_packet_type_t*)buffer; matrix_t my_matrix = packet->m_matrix; // <- BOOOM memcpy(&my_matrix, &packet->m_matrix, sizeof(matrix_t)); // <- works! And then it goes boom. However, this just happens on PowerPC hardware, havent been able to reproduce it on a PC. Neither can i reproduce it locally (ie not sending the data over a socket). So there no problem with What could be wrong? Do i manually need to pad all the data to align or something? That would be odd. Thanks in advance.
Shields up! Rrrrred alert!
Advertisement
Quote:char* buffer = socket.recv();


What exactly does this do?
its just a call to recv() that i simplified in the post.

int recv_size = recvfrom(m_socket, m_buffer, BUFFER_SIZE, 0, (sockaddr*)&socket_address, &address_size);
Shields up! Rrrrred alert!
Is m_buffer dynamically allocated?

I believe that new char[] isn't required to return aligned data, or, at very least, it returns as aligned per char (1 byte boundary).

Also, what does my_packet_type_t look like?

Memory alignment and aliasing can be annoying, this is why it's best to avoid them as much as possible.

One solution would be to define a read float method, then use memcpy in there to read each float individually.

But come to think of it... Doesn't PPC use different byte order altogether, making such reading impossible in the first place?

When you are de-marshalling, there is no guarantee that the source data is aligned correctly for the native data type. For example, if you first write a single byte, and then a float, the float in that buffer will be mis-aligned.

What you should do is use memcpy() to de-marshal, rather than the native "=" operation.

Also, if your matrix class is SSE enhanced, then the buffer needs to be 16-byte aligned, and data returned from malloc()/new[] is only, at best, 8-byte aligned.
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement