Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
sharptooth Avatar asked Dec 05 '25 15:12

sharptooth


1 Answers

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)

like image 175
jcoder Avatar answered Dec 08 '25 15:12

jcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!