Delete aligned memory from another thread

(C ++) I have memory allocated instances allocated on the heap and then deleted in another thread. Codes look like this:

ALIGNED class Obj
{
public: ALIGNED_NEW_DELETE
...
};

Thread 1:
Obj *o = new Obj;  // overloaded new for aligned memory allocation
postTask(o);

Thread 2:
o->runTask();
delete o;  // overloaded delete for aligned memory deletion
// "delete" statement crashes

The delete operator in thread 2 will give a statement error in Visual Studio 2013 (_BLOCK_TYPE_IS_VALID). Oddly enough, if I delete an object in the creation thread, everything works fine.

Why is this happening? What solution?

EDIT:

@ galop1n: Actually, what I'm using right now is the Eigen built-in new / delete operator EIGEN_MAKE_ALIGNED_OPERATOR_NEW. I also tried my own operators, both refused.

For your own operators, please view its source yourself.

For my dispensers:

void* operator new(size_t size){ return alignedMalloc(size, align); }
void operator delete(void* ptr) { alignedFree(ptr); } 
void* operator new[](size_t size) { return alignedMalloc(size, align); }
void operator delete[](void* ptr) { alignedFree(ptr); }  


void* alignedMalloc(size_t size, size_t align)
{
    char* base = (char*)malloc(size + align + sizeof(int));
    if (base == nullptr) 
           ASSERT(0, "memory allocation failed");
    char* unaligned = base + sizeof(int);
    char* aligned = unaligned + align - ((size_t)unaligned & (align - 1));
    ((int*)aligned)[-1] = (int)((size_t)aligned - (size_t)base);
    return aligned;
}

void alignedFree(const void* ptr) {
    int ofs = ((int*)ptr)[-1];
    free((char*)ptr - ofs);
}

And the ALIGNED macro is __declspec (align (16)). It crashes with or without the ALIGNED attribute.

+4
1

, Thread 2, Obj * " Task" : ~ Task() :

class Task 
{
public:
  ~Task();  // <-- not virtual, therefore it crashes
  ...
}

ALIGNED class Obj : public Task 
{ ... }

. , , , : _BLOCK_TYPE_IS_VALID, debug lib , , , , "".

, .

. , , . Dunno, - ; , .

, , .

+1

Source: https://habr.com/ru/post/1525772/


All Articles