Re: Type cast problem with VC++ 2005 Express Edition
"Tim Roberts" <timr@probo.com>, iletisinde sunu yazdi,
news:9pieh5dkk8vt3m75t6b5frho8ukb8j6id4@4ax.com...
"aslan" <aslanski2002@yahoo.com> wrote:
bool happens to be 8-bit integer in VC++6 case, so again it's working
there.
You just aren't paying attention. There is no type smaller than "char" in
C or C++, so sizeof(bool) cannot report less than 1.
HOWEVER, STL contains a special exception for std::vector<bool>, so that
implementations can pack 8 bools into each byte. The MSVC implementation,
EVEN IN VC++6, does this.
I don't use MSVC implementation but the one from Silicon Graphics Computer
Systems, Inc.
When you do this:
std::vector<bool> boo;
boo.reserve(32);
there are only FOUR bytes of data in the vector. FOUR bytes, not 32
bytes.
If you clear 32 bytes, you are overwriting 28 bytes beyond the end of the
array.
OK I tried something else.
struct bool_struct
{
bool a[32];
};
int main(int argc, char**argv)
{
bool_struct* p=new bool_struct;
return 0;
}
so "new bool_struct" ends up by calling the following cb=32.
void * operator new( unsigned int cb )
{
void *res = _nh_malloc( cb, 1 );
return res;
}
So 32 byte is allocated for "bool a[32];"
Also the following quote from MSDN help installed with VC++ 6 which confirms
the size of 1 byte for VC++ 6;
Microsoft Specific
In Visual C++4.2, the Standard C++ header files contained a typedef that
equated bool with int. In Visual C++ 5.0 and later, bool is implemented as a
built-in type with a size of 1 byte. That means that for Visual C++ 4.2, a
call of sizeof(bool) yields 4, while in Visual C++ 5.0 and later, the same
call yields 1. This can cause memory corruption problems if you have defined
structure members of type bool in Visual C++ 4.2 and are mixing object files
(OBJ) and/or DLLs built with the 4.2 and 5.0 or later compilers.
END Microsoft Specific
Allocations happen to be done in units of dwords, so even if you only
reserve 2 bools, you'll actually have 4 bytes. Maybe that's why you
haven't trashed anything important yet.
You have all the code (in include\vector). You can go look it up
yourself.
vector<bool> uses allocator<unsigned int> to allocate memory, but it
passes
the sizes divided by 32 (using _Nw(x)).
--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.