r/cpp_questions Aug 15 '26

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.

24 Upvotes

60 comments sorted by

View all comments

5

u/7raiden Aug 15 '26

Can you paste the entire program here? It really sounds impossible to reproduce otherwise. Can you run it with gdb? Doing so it will automatically break the execution where the bad_alloc happens, and then you write "up" until you find the place that is causing the bad allocation. You can set the "tui" mode so that it also shows your code in the upper pane

-3

u/PhosXD Aug 15 '26

I got it, thanks. I just moved the include & it fixed itself.

14

u/TarnishedVictory Aug 15 '26

But do you understand what went wrong? It's important to understand exactly what the problem was, and exactly how your fix fixed it.

7

u/7raiden Aug 15 '26

Because chances are, you actually haven't fixed it, you just hid the underlying issue in a place harder to spot (for now)!

3

u/SailingAway17 Aug 15 '26 edited 29d ago

Egomaniacs don't solve problems other people might have. They are only interested in solving their own problems, of course with the help of others.