0

I'm having problem with the code below. I'm experiencing different behaviors depending on what IDE I'm using.

Dev-C++: Runs fine. However, if I pass GenerateFileName(0,0) to file.open(), no file is created.

Visual Studio 2013: Runs fine in all cases, however, the name of the file generated looks like

ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌPùD

or something like that, and the file itself has no extension (I expect a .txt file ).

int main()
{
    ofstream file;
    file.open(GenerateFileName(3, 0));
    file << 1 << endl;
    file.close();
    _getch();
}

const char* GenerateFileName(int Instance_nth, int Input_nth)
{
    string filename = to_string(Instance_nth);
    filename += "_";
    filename += to_string(Input_nth);
    filename += ".txt";

    return filename.c_str();
}
Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45
Nam Le
  • 568
  • 5
  • 12

2 Answers2

4
const char* GenerateFileName(int Instance_nth, int Input_nth)
{
    string filename = to_string(Instance_nth);
    filename += "_";
    filename += to_string(Input_nth);
    filename += ".txt";

    return filename.c_str();
}

You're returning a pointer to the data internally stored by filename while it is destroyed with GenerateFileName's ending: the returned value is a dangling pointer, and your code is undefined behaviour.

What you can do is returning a std::string instead of const char*:

std::string GenerateFileName(int Instance_nth, int Input_nth)
{
    string filename = to_string(Instance_nth);
    filename += "_";
    filename += to_string(Input_nth);
    filename += ".txt";

    return filename;
}

Usage would become:

file.open(GenerateFileName(3, 0).c_str());
rocambille
  • 15,398
  • 12
  • 50
  • 68
  • Thanks. But I'm still wondering why the code runs fine on Dev C++ ( except the scenario when I pass GenerateFileName(0, 0) into file.open()) but not on Visual Studio. – Nam Le Nov 24 '16 at 15:34
  • 3
    Undefined behaviour = you can't expect it to run fine for sure, but you can't expect it to crash for sure either. Your code may run fine with some versions of some compilers -- looks like it's the case for the compiler behind your version of Dev C++, but you may have different behaviours with different compilers or even with different versions of the same compiler – rocambille Nov 24 '16 at 15:40
1

This is undefined behavior, because filename is destroyed, once you leave GenenerateFileName function, and file.open is receiving pointer, which is pointing to already destroyed variable data.

Easiest thing here is to return std::string from GenerateFileName and do something like file.open(GenerateFileName(0,0).c_str());

Starl1ght
  • 4,422
  • 1
  • 21
  • 49