2

我正在开发一个成像库,我正在努力处理图像数据数据类型

由于图像可以具有可变数据类型(每像素 8 位,每像素 16 位),我想实现我的图像数据指针

void* pimage_data;

但是 void* 会导致各种讨厌的事情,包括丑陋的指针算术,例如

pimage_data = &((unsigned char*)pimage_parent->m_pdata)[offset_y * pimage_parent->m_pitch + offset_x];

我怀疑这有问题,因为当我将它传递给另一个方法时

CImage* roi = CImage::create_image(size_x, size_y, pimage_parent->m_data_type, pimage_data);

CImage* CImage::create_image(int size_x, int size_y, E_DATA_TYPE data_type, void* pimage)
   {
   assert(size_x > 0);
   assert(size_y > 0);

   CImage* image = new CImage(size_x, size_y, data_type);
   image->m_pdata = pimage;

   return image;

   }

新的回报std::bad_alloc

现在我必须同意 void* 不会直接导致 bad_alloc 但我很确定这里有问题。有什么提示吗?

编辑:

CImage 几乎没有

CImage::CImage(int size_x, int size_y, E_DATA_TYPE data_type)
   {

   assert(size_x > 0);
   assert(size_y > 0);

   // Copy of the parameter to the class members
   this->m_size_x = size_x;
   this->m_size_y = size_y;
   this->m_data_type = data_type;
   this->m_pitch = size_x;

   // The ctor simply create a standalone image for now
   this->m_pimage_child = NULL;
   this->m_pimage_parent = NULL;

   }

尺寸为 x:746, y:325

4

3 回答 3

2

When new throws bad_alloc, that means it couldn't allocate the requested size. The common cause for that is using garbage values which are much greater than intended. (It's possible to actually run out of memory too.) For your code, however, either sizeof(CImage) is really huge or bad_alloc is being thrown from some other new expression.

It looks like you want a constructor rather than create_image, and possibly derived classes (one for each image type) with a factory instead of storing data_type.

于 2010-01-19T03:12:49.140 回答
2

If you need a buffer for raw data with variable BPP, consider just using an array of unsigned char. Encapsulate the access inside a class -- CImage should contain an array that it allocates on construction. Better yet, use a std::vector.

于 2010-01-19T03:15:21.257 回答
1

bad_alloc 可能意味着您的可用内存不足(因为您说 sizeof(CImage) == 28,您很可能会在紧密或无限循环中执行此操作)。这也可能意味着您已经通过以前的顽皮内存行为破坏了 freestore,并且它只是在下一个分配/释放周期中捕获了它。一个好的调试会话可以帮助区分。

于 2010-01-19T03:50:00.413 回答