【问题标题】:Identifier is undefined when deleting a dynamic array [duplicate]删除动态数组时未定义标识符[重复]
【发布时间】:2020-05-15 19:21:47
【问题描述】:

我正在尝试使用CreateDIBSection 捕获位图信息的代码。由于我想让数组的大小(用于保存显示监视器的每个像素值)灵活以适应不同大小的监视器,我创建了一个动态无符号字符数组(每个颜色通道为 1 个字节)。

但是,当我运行程序时,程序在删除数组的部分,接近程序末尾时崩溃了。

我尝试将数组转换回原始类型,即 unsigned char*,因为我怀疑它在传递给 CreateDIBSection() 时被转换为 void**,但它不起作用。

以下是代码,感谢所有建议。

#include <Windows.h>
#include <cstdint>

HWND m_hwnd;

void GetBitMapInfo(const int& x_Coordinate, const int& y_Coordinate, const int& iWidth, const int& iHeight)
{
DWORD imageSize = iWidth * iHeight * 4; 

// Get the display window
HDC displayWindow = GetDC(m_hwnd);
HDC hdc = CreateCompatibleDC(displayWindow);

// Fill in the Bitmap information
BITMAPINFO bmpInfo;
ZeroMemory(&bmpInfo, sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biWidth = iWidth;
bmpInfo.bmiHeader.biHeight = iHeight;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biBitCount = 32;
bmpInfo.bmiHeader.biCompression = BI_RGB;
bmpInfo.bmiHeader.biSizeImage = 0; 
bmpInfo.bmiHeader.biClrUsed = 0;
bmpInfo.bmiHeader.biClrImportant = 0;

// Create the storage for the pixel information
uint8_t* image = new uint8_t[imageSize];

// Populate the storage with the BMP pixel information
HBITMAP hBitmap = CreateDIBSection(hdc, &bmpInfo, DIB_RGB_COLORS, (void**)(&image), nullptr, NULL);

SelectObject(hdc, hBitmap);
BitBlt(hdc, x_Coordinate, y_Coordinate, iWidth, iHeight, displayWindow, 0, 0, SRCCOPY);

delete[] image; //Program crashed here: identifier "image" is undefined
image = nullptr;
DeleteDC(hdc);
DeleteDC(displayWindow);
DeleteObject(hBitmap);

return;
}

int main()
{
    GetBitMapInfo(0, 0, 1920, 1080);    
    return 0;
}

【问题讨论】:

  • 为什么要删除内存数组?应该是“删除图片”;
  • @Mannoj uint8_t* image = new uint8_t[imageSize]; 您需要将new[]delete[] 匹配。但这并不是真正的问题。
  • 是的,你是对的
  • @DanielLangr,感谢您的链接,我按照他们释放资源的方式进行操作,但现在我遇到了一个新问题。我将在单独的问题中发布。

标签: c++ arrays dynamic bitmap window


【解决方案1】:

CreateDIBSection 函数生成指针

... 接收指向 DIB 位值位置的指针。

您为image 分配的内存丢失(内存泄漏),新指针无法传递给delete[](这将导致未定义行为)。 p>

文档指出,使用空指针hSectionCreateDIBSection 分配的内存将由DeleteObject 释放。

【讨论】:

  • 我尝试在不删除动态数组的情况下多次循环我的程序,我意识到存储在数组中的值是不同的,我应该得到相同的值,因为我正在捕获位图信息相同的图像。因此,这让我认为我必须执行删除以清除所有占用的内存。
  • @John5012 这真的取决于CreateDIBSection 在做什么。也许它会在内部分配它给你的新内存?
  • @DanielLangr 错过了,感谢您指出。添加到答案。
  • 一些程序员老兄,谢谢。现在我明白了,不需要为图像分配内存(**ppvBits),因为如果 CreateDIBSection 的 hSection 为 NULL,系统将按照文档中的说明分配内存。
猜你喜欢
  • 2020-04-12
  • 2015-10-11
  • 2021-10-28
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多