【问题标题】:Error on append string - Access violation reading location附加字符串出错 - 访问冲突读取位置
【发布时间】:2021-06-16 08:27:32
【问题描述】:

我正在尝试将数据矩阵公式化为要发送到服务器的字符串。但是在将数据附加到字符串时出现错误。为什么会这样?

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

我的代码:

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, 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 + ","); -> matrix += to_string(rgbValue) + ",";

标签: c++ string string-literals pointer-arithmetic


【解决方案1】:

在此声明中

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

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

你的意思好像是这样的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多