Segmentation failure

Asked

Viewed 189 times

1

I created a class to display a string at the terminal, but in addition to displaying the string, also, displays the following message: "segmentation failure". I debug with GDB, but could not resolve the error. Follow the code below:

#ifndef CONNECTION_H
#define CONNECTION_H

#include<string>
#include<iostream>

using std::string;

class Connection {

public:

   Connection();
  ~Connection(); 

  string conexao;
  string getConexao();

};

#endif // CONNECTION_H




#include"teste.h"

Connection::Connection() 
{
  conexao = "sete de setembro";
}


string Connection::getConexao()

{  
  std::cout << conexao << std::endl;
}


Connection::~Connection()
{

}





#include "teste.h"

int main(void)
{

Connection con;
con.getConexao();

return 0;

}

1 answer

1


You have created a method that returns a string, but did not return anything. Then causes an error.

#include<string>
#include<iostream>

using std::string;
using namespace std;

class Connection {
public:
    Connection();
    string conexao;
    string getConexao();
};

Connection::Connection() {
    conexao = "sete de setembro";
}

string Connection::getConexao() {  
    cout << conexao << endl;
    return conexao;
}

int main(void) {
    Connection con;
    con.getConexao();
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Bigown, Even without the return the error message continues to be displayed.

  • But it needs feedback. I showed you working. If your code has something different, I can’t help. I can only talk about what I’m seeing. Transform into voidalso works, but it would be strange a function that starts with get return nothing. http://ideone.com/KTs5zg

  • I put get to refer to an even return function. I didn’t know that the compiler would understand get, because I thought it was optional.

  • @L.Time A clue that the problem was this is the alert that appears on your compiler when you turn on all alerts. In GCC, this can be done with -Wall and gives the following message: warning: no return statement in function returning non-void [-Wreturn-type]&#xA; } , which means you’re missing something in your function. As fellow @bigown said, get is kind of a default for functions that return values. Don’t use for functions that print things.

  • 1

    Got it, Thanks to Bigown and you Pablo for the clarifications.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.