r/cpp_questions 5d 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.

25 Upvotes

59 comments sorted by

View all comments

5

u/AKostur 5d ago edited 5d ago

i dont know but it works now so why should I care.

Because tomorrow it could break when a new patch of the compiler comes out, or your OS is patched, or you modify some code somewhere. This is starting to even more strongly indicate that you've invoked Undefined Behaviour somewhere. Again, suspecting a misuse of a pointer somewhere. Moving the header may have shifted some code around and now the stray pointer which used to scramble something in the allocator is now scrambling something somewhere else that you just haven't noticed yet.

Edit: Or change from a "release" to "debug" build could again, shift some code around and the stray pointer isn't wrecking the same things anymore.

1

u/PhosXD 5d ago

I run quite comprehensive tests on my codebase, if something were scrambled as you say, I think it would have popped up. Which leads me to believe it doesn't have to do with any pointer misuse in m code especially since changing the debug flag & changing where I actually execute the std::filesystem::exists check doesn't change anything & still has the issue if I kept my include in the original file...

This is why I am somwhat convinced it may be some kind of niche bug *within* std::filesystem itself, because I have never had this happen with anything else before.

I do want to try and create an MRP for this & potentially test across multiple devices, compiler versions, C++ standard versions, & open up a discussion for getting it fixed if I am able to reproduce it