Mikhail Mikhail - 21 days ago 8
C++ Question

Why does VS clam this violates memory?

I needed to enforce some SSE memory boundaries for the code i'm writing but i'm having some trouble with Visual Studio's memory checker. I'm wondering why VS believes there is memory getting corrupted?

#define sse_t float* __restrict
#include <iostream>
#include <assert.h>
#include <stdio.h>
using namespace std;
class AlignedContainer {
public:
AlignedContainer(int n = 0, int frames = 0, size_t align = 16) {

assert((align & (align - 1)) == 0);
int bufferSize = sizeof(float) * n;
for (int i = 0; i < frames; i++) {
int alignedSize = bufferSize + 15;
auto aqbuf = new unsigned char[alignedSize];
auto aligned = reinterpret_cast < unsigned char *>((reinterpret_cast < size_t > (aqbuf) + 15) & ~15); // 16 bit alignment in preperation for SSE
memset(aqbuf, 0, alignedSize); // for debugging, forces memory to instantly allocate
AcqBuffers.push_back(aqbuf);
displayFrames.push_back(aligned);
}
}

~AlignedContainer() {
for (int i = 0; i < AcqBuffers.size(); i++) {
delete[]AcqBuffers[i];
}
AcqBuffers.empty();
displayFrames.empty();
}

inline sse_t operator [] (int i) const {
return (sse_t) displayFrames[i];
}

private:
vector < void *>displayFrames;
vector < void *>AcqBuffers;
};

int main(int argc, char *argv[])
{
int h = 2160;
int w = 2544;
AlignedContainer ac;
ac = AlignedContainer(h * w, 4);
}


Error at the last line.

/***
*static int CheckBytes() - verify byte range set to proper value
*
*Purpose:
* verify byte range set to proper value
*
*Entry:
* unsigned char *pb - pointer to start of byte range
* unsigned char bCheck - value byte range should be set to
* size_t nSize - size of byte range to be checked
*
*Return:
* TRUE - if all bytes in range equal bcheck
* FALSE otherwise
*
*******************************************************************************/
extern "C" static int __cdecl CheckBytes(
unsigned char * pb,
unsigned char bCheck,
size_t nSize
)
{
while (nSize--)
{
if (*pb++ != bCheck)
{
return FALSE;
}
}
return TRUE;
}

Answer

When i tried to run your code i discovered the following:

Your code is missing the rvalue assignment operator. Without it, it appears that the content of AcqBuffers gets moved when you call ac = AlignedContainer(h * w, 4);

Somehow the class still hols the content of AcqBuffers (after being moved) deleting it when destroyed. When the destructor of ac gets called then the destructor delets AcqBuffers again causing runtime error.

To fix this you need to add this:

AlignedContainer& operator = (AlignedContainer && rv)
{
    displayFrames = std::move(rv.displayFrames);
    AcqBuffers = std::move(rv.AcqBuffers);
    return (*this);
}

Raxvan.

Comments