0

I have a struct alignedStruct, and it requires special alignment (SEE ext):

void* operator new(size_t i) { return _aligned_malloc(i, 16); }
void operator delete(void* p) { _aligned_free(p); }

This alignment works fine for unique objects/pointers of alignedStruct, but then I tried to do this:

alignedStruct * arr = new alignedStruct[count];

My application crashes, and the problem is definitely about "alignment of array" (exactly at previous line):

0xC0000005: Access violation reading location 0xFFFFFFFF.

Such crash occur in ~60% of times, also indicates problem is not typical.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Loryan55
  • 325
  • 4
  • 13
  • possible duplicate of [returning aligned memory with new?](http://stackoverflow.com/questions/2660076/returning-aligned-memory-with-new) – Mgetz Jul 31 '13 at 19:29
  • 2
    Are you also redefining `operator new[]` and `operator delete[]` as well? Also, why exactly do you **require** special alignment? Is it SSE-related? – Drew McGowen Jul 31 '13 at 19:29
  • yes! :P How to override new[] correctly? I need this i think – Loryan55 Jul 31 '13 at 19:34
  • @Mgetz Don't you understand my question about array? alignment which question there is about i already have. – Loryan55 Jul 31 '13 at 19:36

1 Answers1

2

I believe what you're looking for is placement new which allows you to use the _aligned_malloc with a constructor properly. Alternatively you can overload operator new[] and operator delete[].

void* operator new[] (std::size_t size)
{
   void * mem = _aligned_malloc(size, 16);
   if(mem == nullptr)
      throw std::bad_alloc;
   return mem;
}
Community
  • 1
  • 1
Mgetz
  • 5,108
  • 2
  • 33
  • 51