c++ - 为什么在返回对象 Mat 时堆损坏?

标签 c++ visual-c++ opencv heap-corruption

我不明白为什么这个程序会出现损坏的堆错误(我正在为 Mat 类使用 OpenCV):

class A {
    private:
    Mat image;      

    static UINT ThreadProc( LPVOID pParam ) {
        A* pThis= (ClientNetwork*)pParam;
        UINT nRet= pThis->DoThreadProc();     // get out of 'static mode'
        return( nRet );
    }
    UINT ClientNetwork::DoThreadProc() {
         vector<uchar> vect;
         while(1) {
             /**** initialize vect and get the image data to decode ****/

             decode(vect);
         }
    }

    public:
    void decode(const vector<uchar>& vectorData){image=imdecode(vectorData, CV_LOAD_IMAGE_COLOR);}
    Mat get_image(){return image;}
    void start() {m_pcThread= AfxBeginThread(ThreadProc, this );}
}

int main() {
    A* a = new A();
    a->start();
    while(1) {
        Mat image = a->get_image();
    }
    delete a;
    return 0;
}

似乎错误来自 Mat image = a->get_image(); 因为如果我返回一个引用而不是对象的拷贝,我就不会再有错误了:

Mat* get_image(){return &image;}

Mat* image = a->get_image();

我读到在 C++ 中返回对象的拷贝比引用更优雅。所以我想知道哪里出了问题。

编辑:Visual Studio 在 a->decode(vect) 中断,但它仅在我返回对象而不是引用时发生。

编辑 2: 我编辑了代码以反射(reflect)完整的程序。我认为问题出在同时复制和修改的共享对象 a 上。我将使用互斥锁查看问题是否仍然存在。

最佳答案

你使用 a 没有初始化它。

int main() {
    A* a;
    vector<uchar> vect;
    while(1) {
        // get the vector of data
        a->decode(vect);

欢迎来到未定义的行为,人口:你。

初始化a以获得更好的结果。

关于c++ - 为什么在返回对象 Mat 时堆损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15330266/

相关文章:

c++ - 编译错误 : undefined reference to‘__atomic_fetch_add_4’

C++ 多重分派(dispatch)

c++ - 在 C++ 中删除 char 数组末尾的输入键值

c++11 - 从包含其他字符的字符串中提取尾随 int

c++ - 如何在 WinCE 设备上获取供应商和产品 ID

image - 图案图像处理

python - 尝试使用 CV2 和 numpy 调整图像的大小和形状

c++ - opengl - 在着色器中使用大型 (100k) 统一数组

c++ - 按值传递 va_list 时发生访问冲突

c++ - C++ 中的 typeid 运算符