Data alignment problems with sizeof and new
- From: astdsoftware <astdsoftware@xxxxxxxxxxxxxxxx>
- Date: Tue, 1 Nov 2005 13:12:03 -0800
I have a strange problem with a project involving classes with data alignment
padding. It appears that, in this particular project, the sizeof and new
operators are not taking the alignment padding into account when calculating
the size of an object. The struct member alignment is set to 8 (/Zp8), and
there are no #pragma pack directives. The test class below shows how, given a
class with the first member being a dword size followed by doubles, the first
double member is padded out to an offset of 8, increasing the memory
footprint by 4 bytes. Using the sizeof() operator outside the scope of the
class, the size returned is the sum of all of the members, but if I use the
sizeof operator inside the constructor, it calculates the right size.
The real problem is that the new operator only allocates enough memory for
the object without any padding, and when the constructor starts initializing
its data members, the last one writes beyond the memory block allocated for
the class. If I move this code to a different project, it works just fine,
but I can't find any project options or anything which might explain this
behavior.
Of course, the problem goes away if I change the alignment to /Zp4, simply
because the padding goes away, but that only works if I don't use anything
smaller than 4 bytes in size.
Any clues would be greatly appreciated!
-----------------------------------------------------------
// TestClass.h
#pragma once
class TestClass
{
public:
TestClass(void);
~TestClass(void);
unsigned int m_dwData; // Offset 0
double m_Data1; // Offset 8
double m_Data2; // Offset 16 (0x10)
double m_Data3; // Offset 24 (0x18)
double m_Data4; // Offset 32 (0x24)
};
-------------------------------------------------------------
// TestClass.cpp
#include "StdAfx.h"
#include ".\testclass.h"
TestClass::TestClass(void)
: m_dwData(0)
, m_Data1(0)
, m_Data2(0)
, m_Data3(0)
, m_Data4(0)
{
int mysize = sizeof(*this); // Evaluates to 28h (Correct Value)
}
TestClass::~TestClass(void)
{
}
--------------------------------------------------------------
// Main.cpp
#include ".\testclass.h"
TestClass* pTest;
pTest = new TestClass;
int tsize = sizeof(*pTest); // Evaluates to 24h (Incorrect Value)
---------------------------------------------------------------
.
- Follow-Ups:
- Re: Data alignment problems with sizeof and new
- From: Doug Harrison [MVP]
- Re: Data alignment problems with sizeof and new
- From: Igor Tandetnik
- Re: Data alignment problems with sizeof and new
- Prev by Date: Re: Drawing HTML text
- Next by Date: Re: Data alignment problems with sizeof and new
- Previous by thread: Re: /Za option
- Next by thread: Re: Data alignment problems with sizeof and new
- Index(es):
Relevant Pages
|