0

The following code gives me seg.fault (see the comment bellow) depending how I define newImagesData. If it's array everything is OK but if defined as a pointer - fault :(

//Mat newImagesData[FIFO_SIZE]; // Mat is a class from opencv
Mat* newImagesData;

void func1( )
{
    ...
    newImagesData = (Mat*)malloc(FIFO_SIZE * sizeof(Mat)); //if *newImagesData
    fifoInit(&newImagesFB, newImagesData, FIFO_SIZE);
    ...
}

void fifoInit(FIFOBuffer* fifo, Mat* imageData, int size)
{
    fifo->data = imageData;
    fifo->end = 0;
}

void fifoWrite(FIFOBuffer* fifo, Mat* frame)
{
    fifo->data[fifo->end] = *frame; // seg fault with *newImagesData ; OK with newImagesData[]
    memcpy(&fifo->data[fifo->end], frame, sizeof(Mat)); // OK with *newImagesData
    ...
}

If I use memcpy() it works fine. I can understand what I'm doing wrong. Any help?

1 Answer 1

7

You should not dynamically allocate cv::Mat objects or arrays using malloc, since this only allocates space for the objects, but does not call their constructor (which must be called in order to instantiate a type such as cv:Mat). Correspondingly, free will not call the required destructor.

You should either use new (coupled with delete) or, preferably, use standard library structures such as std::vector (or 'std::dynarray' in C++14). For example,

std::vector<cv::Mat> newImagesData(FIFO_SIZE); 

std::dynarray<cv::Mat> newInagesData(FIFO_SIZE); // C++14 only

You can then use newImageData as you would use a FIFO_SIZE-length array of cv::Mat objects.

Sign up to request clarification or add additional context in comments.

2 Comments

True. Using new and delete operators guarantees the constructor and destructor get called, which will not happen if you use malloc to allocate memory for a class object.
@user2443309 probably just by pure luck. It looks like undefined behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.