Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Segmentation Fault right at the start of main

Tags:

c++

class

struct

This code below shows a segmentation fault. However, right when I unquote the cout << endl statement, it gets rid of the seg fault. I also put a print statement without endl, and it hit seg fault right at the start of main(). Can someone please help me figure this out? Thanks!

#include <iostream>

using namespace std;

typedef struct node{
    string city;
    node * next;
} Node;

class Vertex{
    public:
        Vertex(string cityName) {
            x->city = cityName;
            x->next = NULL;
        }

        void printCity() {
            cout << x->city << endl;
        }

    private:
        Node * x;
};

int main() {
    //cout << endl;
    Vertex x("Phoenix");
    x.printCity();

    return 0;
}
like image 420
aashman Avatar asked Nov 28 '25 11:11

aashman


2 Answers

You don't appear to be initialising x in your Vertex constructor. This leads to undefined behaviour in dereferencing, so the fact that it only crashes under some circumstances is incidental and irrelevant. You need to fix your undefined behaviour first:

It's not particularly clear why x is a pointer, so consider removing the indirection in its declaration. (*) If using a pointer is intentional, you'll need to allocate some memory to hold the struct and initialise x with it before dereferencing x.

There are also some stylistic issues with this code which can cause you trouble down the line:

  1. You probably want to add the explicit function-specifier to your constructor to avoid accidental implicit conversion from string.
  2. If you keep the pointer field, you'll almost certainly want to replace the automatically generated constructors (default, copy) and implement a destructor. (See the Rule of Three)
like image 66
pmdj Avatar answered Dec 01 '25 00:12

pmdj


Three more things

  1. You can also use a unique_ptr instead of a raw pointer to make sure you don't leak memory, change your code to this
  2. Also since you are accepting the string by value, consider moving it into your node class instance (you can also forward it to the constructor of node)
  3. Prefer nullptr to NULL in C++11 and beyond

Chance your code to this

#include <iostream>
#include <memory>

using namespace std;

typedef struct node{
    string city;
    node * next;
} Node;

class Vertex{
    public:
        Vertex(string cityName) : x{std::make_unique<Node>()} {
            x->city = std::move(cityName);
            x->next = nullptr;
        }

        void printCity() {
            cout << x->city << endl;
        }

    private:
        std::unique_ptr<Node> x;
};

int main() {
    //cout << endl;
    Vertex x("Phoenix");
    x.printCity();

    return 0;
}
like image 33
Curious Avatar answered Nov 30 '25 23:11

Curious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!