Getting std::bad_alloc when trying to open image with exiv2

318 Views Asked by At

Hello I'm trying to read metadata from image using exiv2, but when opening the file I get the following error: Microsoft C++ exception: std::bad_alloc

I'm using default c++ visual studio 2019 compiler.

#include <iostream>
#include "exiv2/exiv2.hpp"

inline bool file_exists(const std::string& name) {
    struct stat buffer;
    return (stat(name.c_str(), &buffer) == 0);
}

int main(void)
{
    try
    {
        Exiv2::XmpParser::initialize();
        ::atexit(Exiv2::XmpParser::terminate);
#ifdef EXV_ENABLE_BMFF
        Exiv2::enableBMFF();
#endif

        const char* file = "E:/img/DJI_0001.jpg";
        if (!file_exists(file)) return 0;
        Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file);
        assert(image.get() != 0);
        image->readMetadata();
    }
    catch (Exiv2::Error& e) {
        std::cout << "Caught Exiv2 exception '" << e.what() << "'\n";
        return -1;
    }
2

There are 2 best solutions below

0
matthias On

This is probably due to an ABI incompatibility between your C++ standard library version and the one exiv2 was compiled with. I suppose you are using a pre-built exiv2 library?

You can check this by calling Exiv2::versionNumber() vs Exiv2::versionString(). The former will work but the latter probably crash because of the std::string involved.

Solution: Do not use the pre-compiled version of exiv2 but compile it yourself within the same dev environment of your main project.

5
Tim On

I had the same problem with the open method. I followed the instructions of matthias and build the lib myself. First the error remained. I then created specific versions for Debug and Release and used the appropriate version for my program. This fixed the issue on my side.

Edit: I also tried the pre-compiled version with my release build. That was also working well.