4

In my matrix class, I allocate aligned memory as such:

/*** main.cpp ***/
#include "matrix.hpp"

int main()
{
    {
        Matrix(15, 17);
    }
    return 0;
}

/** matrix.hpp **/
class Matrix
{
private:
    std::size_t width_, height_;
    double* data_;
public:
    Matrix(std::size_t width, std::size_t height);
    ~Matrix();
};
/** matrix.cpp **/
Matrix::Matrix(std::size_t width, std::size_t height)
: width_(width)
, height_(height)
{
    data_ = new(std::align_val_t{64}) double[width_ * height_];
}

How do I properly delete it?

I tried both

Matrix::~Matrix()
{
    delete[] data_;
}

and

Matrix::~Matrix()
{
    delete[](std::align_val_t{64}, data_);
}

But I get the errors:

SIGTRAP (Trace/breakpoint trap)    
ntdll!RtlIsNonEmptyDirectoryReparsePointAllowed 0x00007ffe5dc390e3  
ntdll!RtlpNtMakeTemporaryKey 0x00007ffe5dc41512  
ntdll!RtlpNtMakeTemporaryKey 0x00007ffe5dc4181a  
ntdll!RtlpNtMakeTemporaryKey 0x00007ffe5dc4a7d9  
ntdll!RtlGetCurrentServiceSessionId 0x00007ffe5db8081d  
ntdll!RtlFreeHeap 0x00007ffe5db7fba1  
msvcrt!free 0x00007ffe5bc09cfc  
Matrix::~Matrix matrix.cpp:15  
main main.cpp:16  
__tmainCRTStartup 0x00000000004013c1
mainCRTStartup 0x00000000004014f6  

where line 15 refers to the line containing either delete[].

I'm using MSys2's g++ 10.1 on Windows10.

edit: If I compile this under WSL with g++ 10.1 it works just fine. So this is probably caused by the Windows port.

infinitezero
  • 1,610
  • 3
  • 14
  • 29
  • 4
    `where line 15` - If that's only like 15 lines, please post a full compilable [MCVE]. – KamilCuk Oct 29 '20 at 17:40
  • Highly related, if not a dupe: https://stackoverflow.com/questions/506518/is-there-any-guarantee-of-alignment-of-address-return-by-cs-new-operation – πάντα ῥεῖ Oct 29 '20 at 17:43
  • 1
    A better way to use aligned memory with placement-new is to use `std::aligned_storage` instead. Is there a reason why you are not simply using `std::vector`, though? – Remy Lebeau Oct 29 '20 at 17:43
  • 2
    Your `Matrix` class does not obey [the rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three) which may be causing this problem. – François Andrieux Oct 29 '20 at 17:44
  • 2
    Strong change that something else has corrupted your heap and it is only being seen when you delete your value. – Michael Dorgan Oct 29 '20 at 17:55
  • @FrançoisAndrieux There's no need right now, as I only construct and destruct the element. No copying/moving. – infinitezero Oct 29 '20 at 17:58
  • If I use it without the align option in `new`, it works just fine. So I highly suspect that is the reason. – infinitezero Oct 29 '20 at 18:01
  • Not seeing the problem w clang++ / c++11. BTW, you are missing ';' on `~Matrix()` declaration. What compiler/environment are you using? – wcochran Oct 29 '20 at 18:19
  • @wcochran as stated, this compiles fine on WSL but not with MSYS's g++ – infinitezero Oct 29 '20 at 20:45

0 Answers0