1
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.

ophilbinbriscoe
  • 137
  • 1
  • 8

1 Answers1

0

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).

Nikita
  • 6,270
  • 2
  • 24
  • 37
  • If I use `new` it will be allocated on the heap, is there a way to initialize an object instance and have it belong to (for example) the scope from which this method was called? None of primers on pointers that I've followed have touched on this. – ophilbinbriscoe Sep 11 '16 at 20:53
  • @ophilbinbriscoe `CImg` class has [copy constructor](http://cimg.eu/reference/structcimg__library_1_1CImg.html#aff97beaa34b9061351711dcdaed85c58) and [`move_to`](http://cimg.eu/reference/structcimg__library_1_1CImg.html#a09aeb03ffe6512209f64b92fbef9574c) method. You can declare `img` as `CImg img;` and simply assign `img = CImg( filename );` – Nikita Sep 11 '16 at 21:07