c++ - 静态分配和动态分配返回不同的答案

标签 c++

<分区>

模组 - 请关闭此问题。我发现了代码中的错误。很遗憾,我无法删除它。

下面两个代码片段有什么区别吗? 也许关于填充?因为关于第一个(静态分配),我得到了奇怪的图像。第二个没问题。

产生扭曲的图像(我猜缺少蓝色并且像素发生偏移)

function1(char *image) { 
 char image_data_[image_info_.imgSize];
 memcpy(image_data_, image, image_info_.imgSize); // 144000 bytes
 cv::Mat color_image_opencv(image_info_.height, image_info_.width, CV_8UC3, image_data_);
 cv::imwrite("image.png", color_image_opencv);
}

和(这行得通)

function2(char *image) { 
 char *image_data_ = NULL;
 image_data_ = reinterpret_cast<char*>(malloc(image_info_.imgSize));
 memcpy(image_data_, image, image_info_.imgSize);
 cv::Mat color_image_opencv(image_info_.height, image_info_.width, CV_8UC3, image_data_);
 cv::imwrite("image.png", color_image_opencv);
}

最佳答案

我们可以使用我们的心理调试能力来推断您正在从函数返回 cv::Mat,或者以其他方式将其生命周期延长到它指向的 char 数组之外。虽然使用 malloc() 时,用于存储图像字节的内存在显式释放之前一直可用,但与自动变量相比,一旦图像数据超出范围,您就不能使用它。

documentation对于您正在使用的 cv::Mat 构造函数说:

Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.

当然,当他们说“照顾好它”时,他们的意思并不是“在销毁 cv::Mat 之前先销毁它。”

关于c++ - 静态分配和动态分配返回不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51425284/

相关文章:

c++ - 我可以对 `int file = open(path, flag);` 做些什么吗?

c++ - 未找到 Fmod 常量 (FMOD_HARDWARE)

c++ - 从工作线程输出到 cin (c++)

c++ - 在 C++ 和 Ncurses 中显示 % 符号

c++ - 使用默认模板参数/参数与以下模板化函数有何区别

c++ - 在应该按引用传递的地方按值传递指针

c++ - 计算 double 分子和分母的最准确方法

c++ - 当我不确定输入是什么时使用什么变量?

c++ - 这是 clang++/g++ 中的错误吗?

c++ - 传递 std::shared_ptr 作为对 lambda 捕获列表的引用 (C++)