D
derek.google
I have an application that's crashing because of an alignment problem,
and this is the smallest program that demonstrates what's happening:
int main() {
struct Message {
unsigned short size;
};
const int START_INDEX = 1;
char* buffer = new char[1024];
Message* msg = (Message*)&buffer[START_INDEX];
unsigned short s = msg->size;
delete[] buffer;
}
This program dumps core (Bus Error) when START_INDEX is 1, 3, 5, etc.,
but it doesn't crash when START_INDEX is 0, 2, 4, etc.
This only happens when I compile and run on SPARC/Solaris. (I've tried
compiling with GCC 3.4 and Sun Forte and both produce the same
behavior, so I don't think I can fault the compiler.) The program
doesn't crash for any value of START_INDEX on x86/Windows with VC7.
I thought C++ guaranteed that a dynamically allocated array (i.e. char*
buffer) was suitable alignment-wise to hold any structure (i.e. struct
Message). Clearly that's not the case here, because I can only access
the unsigned short msg->size on word boundaries (i.e. START_INDEX = 0,
2, 4, etc.).
Can someone explain what's going on here?
Derek
and this is the smallest program that demonstrates what's happening:
int main() {
struct Message {
unsigned short size;
};
const int START_INDEX = 1;
char* buffer = new char[1024];
Message* msg = (Message*)&buffer[START_INDEX];
unsigned short s = msg->size;
delete[] buffer;
}
This program dumps core (Bus Error) when START_INDEX is 1, 3, 5, etc.,
but it doesn't crash when START_INDEX is 0, 2, 4, etc.
This only happens when I compile and run on SPARC/Solaris. (I've tried
compiling with GCC 3.4 and Sun Forte and both produce the same
behavior, so I don't think I can fault the compiler.) The program
doesn't crash for any value of START_INDEX on x86/Windows with VC7.
I thought C++ guaranteed that a dynamically allocated array (i.e. char*
buffer) was suitable alignment-wise to hold any structure (i.e. struct
Message). Clearly that's not the case here, because I can only access
the unsigned short msg->size on word boundaries (i.e. START_INDEX = 0,
2, 4, etc.).
Can someone explain what's going on here?
Derek