i_ll_be_back i_ll_be_back - 1 month ago 12
C++ Question

float type Buffer contents lost after creating object C++

I have a class that contains a float type buffer which points to an array of RGB values. The buffer is created and stored properly but when I return the instance of this class throught a function to the main() the memory of the buffer is unreadable. Here is the initial class:

namespace imaging
{
typedef float component_t;

class Image
{
protected:
component_t * buffer;
unsigned int width, height;
public:
Image(unsigned int width, unsigned int height, const component_t * data_ptr) {
this->width = width;
this->height = height;
this->setData(data_ptr);
this->buffer = const_cast<component_t *>(data_ptr);
}

component_t getRedValPixel(unsigned int x, unsigned int y) const {
int pos = x * this->width * 3;
component_t red;
red = this->buffer[pos];
return r;
}
}
}


To create an instance of this class I use a readImage(char* filepath) method that after loading the data has this return statement:

return &Image(width, height, buffer);


Here is the code in the main() function:

Image* image = readIamge(filepath);
int width = image->getWidth(); //retrieves it correctly
int height = image->getHeight(); //retrieves it correctly
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cout << image->getRedValPixel(i,j);
}
}

aks aks
Answer

return &Image(width, height, buffer); will return the address of locally created object in the stack, which will be destroyed just after loosing the scope( i.e. the return statement ).

Solution is to allocate the Image object in heap. E.g.

main()
{
....
Image* image = NULL;
readImage(filepath, image );
int width = image->getWidth(); //retrieves it correctly
int height = image->getHeight(); //retrieves it correctly
for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
        cout << image->getRedValPixel(i,j);
    }
}
delete image;
image = NULL
...
}


void readImage(char* filepath, Image* o_pBuffer ) 
{
   .....
   o_pBuffer = new Image(width, height, buffer);
   return o_pBuffer;
}

or

main()
{
....
Image* image = NULL;
image = readImage(filepath );
int width = image->getWidth(); //retrieves it correctly
int height = image->getHeight(); //retrieves it correctly
for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
        cout << image->getRedValPixel(i,j);
    }
}
delete image;
image = NULL
...
}


Image* readImage(char* filepath ) 
{
   .....
   Image* o_pBuffer = new Image(width, height, buffer);
   return o_pBuffer;
}