c++ - Strange error reading file -


i'm compiling in mingw on windows , using gdb debug application. i'm getting output when trying read file disk:

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

here 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 open file: " << filename << std::endl;     }      return ret.c_str(); } 

here 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 explain behavior? thanks!

this undefined behavior.

 return ret.c_str(); 

the object ret has local function scope. object gets destroyed when function returns, , of internal memory gets deallocated.

it's c_str() method returns pointer that's no longer valid, after object gets destroyed. function returns, c_str() pointer no longer valid.

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


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -