当我尝试调整窗口宽度时出现堆损坏

问题描述 投票:0回答:1

我正在尝试动态调整窗口大小,并且认为所有代码都是正确的,但是当我尝试更改宽度值时,它给了堆损坏错误内存中的特定位置(检测到堆损坏:在正常块之后( #11614) 在 0x0000024D27EAA830 - CRT 检测到应用程序在堆缓冲区结束后写入内存。)。这是我的代码:

HDC Device, CmpDevice;
HBITMAP hbitmap;
BITMAPINFOHEADER bi;

Device = GetDC(hwnd);
CmpDevice = CreateCompatibleDC(Device);
SetStretchBltMode(CmpDevice, COLORONCOLOR);

RECT rc;
GetWindowRect(hwnd, &rc);
RECT rcf = { (rc.right / 2) - (InputF[0] / 2), (rc.bottom / 2) - (InputF[1] / 2), (rc.right / 2) + (InputF[0] / 2), (rc.bottom / 2) + (InputF[1] / 2) };
int width = (rcf.right - rcf.left);
int height = (rcf.bottom - rcf.top);

Mat src(Size(width, height), CV_8UC3);

hbitmap = CreateCompatibleBitmap(Device, width, height);
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = width;
bi.biHeight = -height;
bi.biBitCount = 24;
bi.biCompression = BI_RGB;
bi.biPlanes = 1;
bi.biClrUsed = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrImportant = 0;

SelectObject(CmpDevice, hbitmap);

StretchBlt(CmpDevice, 0, 0, width, height, Device, rcf.left, rcf.top, width, height, SRCCOPY);

GetDIBits(CmpDevice, hbitmap, 0, height, src.data, (BITMAPINFO*)&bi, DIB_RGB_COLORS);


DeleteDC(CmpDevice);
ReleaseDC(hwnd, Device);
DeleteObject(hbitmap);

return src;

我尝试删除src的数据,释放数据并取消分配数据。在我看到这些不起作用后,我尝试将图片数据复制到另一个数据,创建图片后,我删除了数据但没有'也不起作用。除了这些之外,我什么也做不了。我可以更改图片的高度值,但是当我尝试更改宽度时,它会给出堆损坏错误。我尝试过使用 new 语句创建的变量,然后删除创建图片后删除语句,但它也不起作用。

c++ opencv memory heap-memory heap-corruption
1个回答
0
投票

当宽度更改时,src 矩阵的大小计算存在潜在问题。确保 src 矩阵足够大以容纳新的宽度。

正确分配 src -

的修改后的代码
int width = (rcf.right - rcf.left);
int height = (rcf.bottom - rcf.top);

Mat src(Size(width, height), CV_8UC3);

// ... rest of your code

// Ensure proper allocation for src.data
src.create(height, width, CV_8UC3);

// ... rest of your code

潜在的错误在于改变宽度后没有更新src矩阵的大小。如果新宽度大于原始宽度,则需要确保适当调整 src 矩阵的大小。这里使用 create 函数为具有新维度的矩阵分配所需的内存。

此修改可确保 src 在宽度更改时有足够的空间来存储像素数据,从而防止潜在的堆损坏错误。

希望有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.