问题
I am using libjpeg to transform image buffer from OpenCV Mat and write it to a memory location
Here is the code:
bool mat2jpeg(cv::Mat frame, unsigned char **outbuffer
, long unsigned int *outlen) {
unsigned char *outdata = frame.data;
struct jpeg_compress_struct cinfo = { 0 };
struct jpeg_error_mgr jerr;
JSAMPROW row_ptr[1];
int row_stride;
*outbuffer = NULL;
*outlen = 0;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_mem_dest(&cinfo, outbuffer, outlen);
jpeg_set_quality(&cinfo, JPEG_QUALITY, TRUE);
cinfo.image_width = frame.cols;
cinfo.image_height = frame.rows;
cinfo.input_components = 1;
cinfo.in_color_space = JCS_GRAYSCALE;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo, TRUE);
row_stride = frame.cols;
while (cinfo.next_scanline < cinfo.image_height) {
row_ptr[0] = &outdata[cinfo.next_scanline * row_stride];
jpeg_write_scanlines(&cinfo, row_ptr, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
return true;
}
The thing is I cannot deallocate outbuffer anywhere.
This is how I am using the function:
long unsigned int * __size__ = nullptr;
unsigned char * _buf = nullptr;
mat2jpeg(_img, &_buf, __size__);
both free(_buf) and free(*_buf) fails it seems i am trying to free the head of heap by doing so.
and mat2jpeg won't accept a pointer to pointer for outbuffer. any idea?
回答1:
I think your problem may be with your __size__
variable. Its not allocated anywhere. According to my reading of the libjpeg source code that means the buffer is never allocated and the program calls a fatal error function.
I think you need to call it like this:
long unsigned int __size__ = 0; // not a pointer
unsigned char * _buf = nullptr;
mat2jpeg(_img, &_buf, &__size__); // send address of __size__
Then you should be able to deallocate the buffer with:
free(_buf);
回答2:
I have verified that it is the dll that caused the issue. I tried to recompiled libjpeg as static library and everything now works like a charm.
来源:https://stackoverflow.com/questions/32587235/how-to-release-buffer-created-by-libjpeg