Reputation: 1
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?
Upvotes: 0
Views: 630
Reputation: 227438
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.
Upvotes: 7