ea********@citiz.net wrote:
For example:
the
msg = temp_buf;
is alwawys ok?
//test_msg.cpp
struct msg_head
{
char a01[4];
char a02[4];
char a03[4];
char a04[4];
char a05[4];
char a06[4];
char a07[4];
char a08[4];
char a09[4];
char a10[4];
char a11[4];
};
int main(void)
{
struct msg_head * msg;
char *p_temp_buf = new char[2024];
...
msg = (struct msg_head *)p_temp_buf;
...
delete p_temp_buf;
return 0;
}
As per the Standard, it is probably undefined behavior. In practice, it
is "ok" in the sense you will not access wrong memory. The structure may
not have its normal (for the compiler/architecture) alignment though
(this especially often will happen with your second example where you
use the buffer on stack). This should not be a problem if you operate
with the character fields only but may be a problem (like bus error) if
you, for example, assign to or even from such structure as a whole and
the compiler generates some optimized code. The following hack would
take care of this problem, most of the time for 64- or less- bit
architectures:
const int WHOLE_LENGTH = 2031;
const int GUARANTEED_LENGTH = 2024;
char *p_allocated_temp_buf = new char[WHOLE_LENGTH];
char *p_temp_buf = ((p_allocated_temp_buf - 1) >> 3) << 3;
if(p_temp_buf != p_allocated_temp_buf) p_temp_buf += 8;
// ... use p_temp_buf for up to Guaranteed_length
delete [] p_allocated_temp_buf;