Skip to content
Advertisement

Segmentation fault while trying to return a pointer to object from a method

g++ throw me ‘segmentation fault’ while I’m trying to return an object of a classB from a method of a classA. I don’t know how to fix this error, if anybody can tell me why this error happens, I would be grateful. So… here is the code:

classA.h

#include "classB.h"
#ifndef _CLASS_A_H_
#define _CLASS_A_H_
class ClassA{
private:
    int id;
    ClassB *ptr_classB;
public:
    ClassA();
    ClassA(int id, std::string name);

    inline void setID(int id){this->id = id;}

    inline int getID(){return this->id;}

    inline ClassB getClassB(){return this->ptr_classB;}

};

#endif

classA.cpp

#include "classA.h"
#include "classB.h"

ClassA::ClassA(){
    this->id = 0;
    ptr_classB = new ClassB();
}

classB.h

#ifndef _CLASS_B_H
#define _CLASS_B_H

class ClassB{
private:
    std::string name;
public:
    ClassB();
    inline std::string getName(){return this->name;}
};
#endif

classB.cpp

#include <string>
#include "classB.h"

ClassB::ClassB(){
    this->name = "default";
}

main.cpp

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

using namespace std;

int main(){
    ClassA *ptr_classA = new ClassA();

    cout << ptr_classA->getClassB().getName()  << endl;
    //asd

    return 0;
}

Makefile

SRC = src

INC = include

OBJ = obj

BIN = bin

LIB = lib

CXX = g++

CPPFLAGS = -c -I$(INC)/ -std=c++11

all: $(BIN)/main

$(BIN)/main: $(OBJ)/main.o

$(CXX) -o $(BIN)/main $(OBJ)/main.o -Llib/ -lclasses

$(OBJ)/main.o: $(SRC)/main.cpp

$(CXX) $(CPPFLAGS) $(SRC)/main.cpp -o $(OBJ)/main.o

$(OBJ)/classA.o: $(SRC)/classA.cpp $(INC)/classA.h $(INC)/classB.h

$(CXX) $(CPPFLAGS) $(SRC)/classA.cpp -o $(OBJ)/classA.o

$(OBJ)/classB.o: $(SRC)/classB.cpp $(INC)/classB.h

$(CXX) $(CPPFLAGS) $(SRC)/classB.cpp -o $(OBJ)/classB.o

$(LIB)/libclasses.a: $(OBJ)/classA.o

ar rsv $(LIB)/libclasses.a $(OBJ)/classA.o 

Advertisement

Answer

Cleaned code :

class ClassA ;
class ClassB ;

class ClassB{
private:
    int n;
public:
    ClassB();
    inline void set_n(int n){this->n =n;}
    inline int get_n(){return this->n;}

};

class ClassA{
private:
    ClassB *ptr_classb;
public:
    ClassA();
    inline ClassB getClassBObject(){return *ptr_classb;}
};

ClassB::ClassB(){
    this->n = 0;
}

ClassA::ClassA(){
    ptr_classb = new ClassB();
}

#include <iostream>

int main(){
    ClassA *ptr_classA = new ClassA();

    std::cout << ptr_classA->getClassBObject().get_n() << std::endl;

    return 0;
}

compile and execute fine after correcting errors at COMPIL time, which make me wonder : how in hell did you manage to compile this to got segfault ?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement