微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

附加字符串错误 - 访问冲突读取位置

如何解决附加字符串错误 - 访问冲突读取位置

我正在尝试将数据矩阵制定为字符串以发送到服务器。但是在将数据附加到字符串时出现错误。为什么会发生这种情况?

我要发送的数据是位图图像像素。

我的代码

string getPixelsFromBitmap(Bitmap& bitmap) {
    //Pass up the width and height,as these are useful for accessing pixels in the vector o' vectors.
    int width = bitmap.GetWidth();
    int height = bitmap.GetHeight();

    auto* bitmapData = new Gdiplus::BitmapData;

    //Lock the whole bitmap so we can read pixel data easily.
    Gdiplus::Rect rect(0,width,height);
    bitmap.LockBits(&rect,Gdiplus::ImageLockModeRead,PixelFormat32bppARGB,bitmapData);

    //Get the individual pixels from the locked area.
    auto* pixels = static_cast<unsigned*>(bitmapData->Scan0);

    //Vector of vectors; each vector is a column.
    //std::vector<std::vector<unsigned>> resultPixels(width,std::vector<unsigned>(height));

    //todo fix string 
    string matrix("");

    const int stride = abs(bitmapData->Stride);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            //Get the pixel colour from the pixels array which we got earlier.
            const unsigned pxColor = pixels[y * stride / 4 + x];

            //Get each individual colour component. Bitmap colours are in reverse order.
            const unsigned red = (pxColor & 0xFF0000) >> 16;
            const unsigned green = (pxColor & 0xFF00) >> 8;
            const unsigned blue = pxColor & 0xFF;

            //Combine the values in a more typical RGB format (as opposed to the bitmap way).
            const int rgbValue = RGB(red,green,blue);

            //Assign this RGB value to the pixel location in the vector o' vectors.
            //resultPixels[x][y] = rgbValue;

            matrix += string(rgbValue + ",");
        }
        matrix += string(".");
    }
    //Unlock the bits that we locked before.
    bitmap.UnlockBits(bitmapData);
    return matrix;
}

解决方法

在本声明中

matrix += string(rgbValue + ",");

参数表达式表示一个带有指针算术的表达式,在 const char * (",") 类型的指针表达式中添加了整数值 rgbValue,这显然会导致访问内存超出字符串文字 ","

你的意思好像是这样的

matrix += string( std::to_string( rgbValue ) + ",");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。