Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bad alloc from variable shadowing?

The executable from the following code

#include <iostream>
#include <filesystem>

int main(void) {    
  std::string filename = "/home/amat/test.txt";
  if (true) {
    std::filesystem::path filename = std::filesystem::path(filename);
    std::cout << "Filename (path): " << filename.string() << std::endl;
  }
  std::cout << "Filename (string): " << filename << std::endl;
  return 0;
}

terminates with

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

Why does this exactly happen? Not that one should seriously write code like this, but still, shouldn’t variable shadowing work here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The std::filesystem::path constructor accepts a reference, yes, but why does it break?

>Solution :

In this line:

std::filesystem::path filename = std::filesystem::path(filename);

The filename used as an initializer is not the one you declared before the if, but rather the one that is just being declared in the current line.

But since its lifetime hasn’t started yet you invoke undefined behavior.

clang is giving a proper warning about it:

warning: variable 'filename' is uninitialized when used within its own initialization

Live demo

Note that the filename you declared before the if is actually not relevant here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading