20 Lines program crashes continue

closed account (4i67ko23)
Hi there,
I'm learning to work with functions,, it isn't my first work, my second.
It crashes continue without reason. It's really simple, so why crashing?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <windows.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
//-----------------------------------------------------------
using namespace std;
//-----------------------------------------------------------
string readfile(string IN_FILE_NAME)
{ 
    string line;
    ifstream myfile (IN_FILE_NAME.c_str());
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            cout << line << endl;
        }
        myfile.close();
    }
    else cout << "Unable to open file"; 
}
//-----------------------------------------------------------
int main()
{
    //writefile("TEST123", "mathijs_text_1");//1
    readfile("abc123.txt");
    Sleep(10000);
}

The function readfile is expected to return a string. You are not returning a string.

The compiler doesn't care. It will still treat whatever data is in the place where returned variables go as a string. This means it is treating some random data as a string. When the time comes to destruct that string, it is trying to call a string destruction function on something that is not a string. This is very, very bad.

Your compiler ideally should warn you about this sort of thing. If it does not, you need to turn up the warning level. The g++ compiler says this, for example:
In function ‘std::string readfile(std::string)’:
 warning: no return statement in function returning non-void [-Wreturn-type]


Clang says this:
 warning: control reaches end of non-void function [-Wreturn-type]


Turn up warnings on your compiler, and listen to what they say.


Your ptogram has underfined behavior because function readfile has no return value thoug it is declared that is returns an object of type std::string. Change its declaration the following way

void readfile( const string &IN_FILE_NAME )
closed account (4i67ko23)
Edit;
Already found!
I wasn't forget to add "return (line)" but I had to!
Problem fixed
Last edited on
closed account (4i67ko23)
Hi, I see your commend now, we posted all at the same time :D
the problem was "return"
Topic archived. No new replies allowed.