What happens if my Visual C++ custom memory allocator returns a block not properly aligned?
In my Visual C++ program I use a custom operator new
that uses malloc()
to allocate memory. My custom operator new
stores extra data in the first 4 bytes of memory and returns an offset pointer as the beginning of the block (the program is 32 bit):
void* oper开发者_开发知识库ator new( size_t size )
{
size += sizeof( int );//assume it doesn't overflow
int* result = static_cast<int*>( malloc( size ) );
if( result == 0 ) {
throw std::bad_alloc;
}
*result = ... //write extra data
return result + 1;
}
Now if caller code wants to store a variable of size 64 bits (__int64
or double
) the block will not be properly aligned for that.
What problems can this cause in a 32-bit Windows program?
On 32 bit windows it will just potentially be slower as the hardware can deal with unaligned data accesses, just more slowly.
On other operating systems / platforms it will likely cause a crash (Or VERY slow performance as the OS catches the unaligned memory access and simulates it for you in some cases)
精彩评论