bustedware
bustedware

Reputation: 324

Strange error reading file

I'm compiling in mingw on windows and using gdb to debug my application. I'm getting this output when trying to read a file from disk:

processfile (type=35633,
source=0xec4d6c "î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_î_"...) at main.cpp:5

Here is my read file function:

const char* read_file_contents(const char* filename)
{
    string ret = "";
    string line;
    ifstream ifs(filename);
    if (ifs.is_open()) {
        while (getline(ifs, line)){
            ret += line + '\n';
        }
    } else {
        std::cout << "failed to open file: " << filename << std::endl;
    }

    return ret.c_str();
}

Here is my main:

#include <iostream>
#include "FileOps.h"

void test_func2(const char* test) {
    std::cout << strlen(test) << std::endl;
    std::cout << test << std::endl;
}

void test_func1(const char* test) {
    test_func2(test);
}

int main(int argc, char** argv)
{
    test_func1(read_file_contents("test.txt"));
    return 0;
}

Can someone explain this behavior? Thanks!

Upvotes: 1

Views: 35

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

This is undefined behavior.

 return ret.c_str();

The object ret has a local function scope. This object gets destroyed when this function returns, and all of its internal memory gets deallocated.

It's c_str() method returns a pointer that's no longer valid, after the object gets destroyed. As soon as this function returns, the c_str() pointer is no longer valid.

The pointer that's returned by c_str() is only valid until the std::string object is modified, or it gets destroyed.

Upvotes: 3

Related Questions