Ask Your Question

Revision history [back]

help finding memory corruption in code that writes to a cv::Mat

Please note, I am not the author of the code that has the problem below. I am having trouble running the https://github.com/CMU-Perceptual-Computing-Lab/openpose that uses opencv.

You can see the valgrind report here: https://github.com/CMU-Perceptual-Computing-Lab/openpose/files/1248462/valgrind-output.txt

Valgrind reports that the code writes 1 byte past allocated memory in this function: https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/utilities/openCv.cpp

void floatPtrToUCharCvMat(cv::Mat& cvMat, const float* const floatImage, const Point<int>& resolutionSize, const int resolutionChannels)
{   
    try 
    {   
        // float* (deep net format): C x H x W 
        // cv::Mat (OpenCV format): H x W x C 
        if (cvMat.rows != resolutionSize.y || cvMat.cols != resolutionSize.x || cvMat.type() != CV_8UC3)
            cvMat = cv::Mat(resolutionSize.y, resolutionSize.x, CV_8UC3);
        const auto offsetBetweenChannels = resolutionSize.x * resolutionSize.y;
        for (auto c = 0; c < resolutionChannels; c++)
        {   
            const auto offsetChannelC = c*offsetBetweenChannels;
            for (auto y = 0; y < resolutionSize.y; y++)
            {   
                const auto floatImageOffsetY = offsetChannelC + y*resolutionSize.x;
                for (auto x = 0; x < resolutionSize.x; x++)
                {   
                    const auto value = uchar(   fastTruncate(intRound(floatImage[floatImageOffsetY + x]), 0, 255)   );  
                    *(cvMat.ptr<uchar>(y) + x*resolutionChannels + c) = value;
                }   
            }   
        }   
    }   
    catch (const std::exception& e)
    {   
        error(e.what(), __LINE__, __FUNCTION__, __FILE__);
    }   
}

This code looks pretty scary because it breaks encapsulation.

*(cvMat.ptr<uchar>(y) + x*resolutionChannels + c) = value;

It would be so much cleaner if it was cvMat[y][x][c] = value or cvMat.setValue(x, y, c, value);

Can you tell me if this code looks correct to you? I think the function is called many times without a memory issue being reported by valgrind.