views:

90

answers:

3

I'm developping an imaging library and I'm struggling with the image data datatype

Since images can have variable datatypes (8 bits per pixel, 16 bits per pixel) I thought of implementing my image data pointer to

void* pimage_data;

however void* leads to all kind of nastiness including ugly pointer arithmetics such as

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

I suspect that something is wrong with this since when I pass it to another method

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;

   }

the new returns std::bad_alloc

Now I must agree that void* does not directly lead to bad_alloc but I'm pretty sure something is wrong with it here. Any hints?

EDIT:

CImage does close to nothing

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;

   }

sizes are x:746, y:325

+2  A: 

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.

Roger Pate
sizeof(CImage) == 28
Eric
+2  A: 

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.

rlbond
+1  A: 

bad_alloc can mean you are out of free memory (since you say sizeof(CImage) == 28, you would most likely be doing it in a tight or infinite loop). It can also mean you have corrupted the freestore though previous naughty memory behavior and it just caught it on the next allocation/release cycle. A good debugging session can help tell the difference.

Todd Gardner
Accepted for the corrupted freestore. I was overwriting memory somewhere else and only sometimes the new would kill it all
Eric