Search code examples
c++sizedimensioncimgnegative-integer

Why does my CImg<float> have negative width and height?


CImg<float>* img = NULL;
bool loaded;

while ( !loaded )
{
    loaded = true;
    try
    {
        img = &CImg<float>( filename );
    }
    catch ( CImgException )
    {
        loaded = false;
        fprintf( stdout, "ERROR: could not load %smap file.\n", mapname );
    }
}

When I enter a valid image filename that CImg is able to find and read, img.width() and img.height() both return -858993460. According to the documentation, img.width()'s return type is int, but the value if fetches is img._width, an unsigned int.


Solution

  • As GManNickG mentioned in the comment, at line img = &CImg<float>( filename ); temporary object of type CImg<float> created and you stores it's address into img variable. This temporary object is only valid inside the block:

    try
    {
      img = &CImg<float>( filename );
    }
    

    It's destructed when execution leaves this scope and you've got invalid pointer with some random content (e.g. -858993460 in _width field).