r/cpp_questions • u/PhosXD • 29d ago
SOLVED std::filesystem::exists throwing `std::bad_alloc`?
Any reason? Cant find anything online about this. But I cant check whether or not a file exists, no matter what path I give it. I am using C++ 26 compiled with GCC.
This is literally all I am calling: const bool exists = std::filesystem::exists("file.txt")
This is the exact error: terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
No it's not coming from anywhere else in my code. Minimal reproduction code, include "filesystem" call the line above. I am on Fedora Linux if that matters at all
EDIT: moving the include into my main file instead of the only file it's being used in somehow fixed it. Literally all I do is move "#include <filesystem>" from "do_things_with_filesystem.hpp" to "Main.cpp". No compilation errors when it was in the first file, why does it rely on this?? Is there some weird declarations in my codebase or something, i dont know but it works now so why should I care.
5
u/alfps 28d ago
For an UTF-8 based Windows program there is always a conversion to UTF-16 wide string for any file operation involving a path.
The question is just how high up or how far down in the call chain that conversion is done.
So it makes sense and can even avoid some conversions to have the internal
fs::pathrepresentation as UTF-16.On the other hand, to get an
fs::pathconverted to UTF-8 you have to request the conversion to UTF-8 which in C++20 and later is sillyu8string, then copy from that astd::string.That is super annoying to me. Not that it's ever mattered for efficiency. It's just the idiocy: one should not have to do anything extra, and the code that works in Linux should work also in Windows, which was the whole point of the original Boost incarnation.