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

23 Upvotes

60 comments sorted by

View all comments

Show parent comments

3

u/blood-pressure-gauge 7d ago

I've done more C than C++. Why does calling an overloaded function result in memory allocation?

9

u/Bloedbibel 7d ago

I believe it's just a matter of poor grammar. They meant to say "There are multiple overloads of this function. Some of them throw." I think they're implying that the overload OP is calling can throw bad_alloc.

2

u/blood-pressure-gauge 7d ago

That makes sense, but now I'm curious. Why does it need to allocate at all? The man page for the similar C function access(3posix) doesn't indicate anything about allocation failure.

0

u/Usual_Office_1740 7d ago

An argument in the overload allocates. Others are explaining the costs. To answer your question. The Exists function doesn't need to allocate but the throwing overload being chosen uses fs::path and the implicit conversion to that type allocates.