简体   繁体   中英

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* operator 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM