Weird Segmentation Fault right at the start of the main
This code below shows a segmentation fault. However, when I dismiss the operator cout << endl
, it gets rid of the seg error. I also put the print statement without endl
and it hit the seg error right at the start main()
. Can someone please help me understand this? Thank!
#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;
}
source to share
You don't seem to be initializing x
in your constructor Vertex
. This leads to undefined behavior when dereferenced, so the fact that it only crashes under some circumstances is random and irrelevant. First you need to fix the undefined behavior:
It is not clear why x is a pointer, so consider removing indirection in its declaration. ( *
) If using a pointer is intentional, you need to allocate some memory to store the structure and initialize x with it before dereferencing x.
There are also some stylistic issues with this code that can cause line problems:
- You probably want to add a function specifier
explicit
to your constructor to avoid accidental implicit conversion fromstring
. - If you are storing the pointer field, you will almost certainly want to replace the auto-generated constructors (default, copy) and implement a destructor. (See Rule of Three )
source to share
Three more things
- You can also use
unique_ptr
instead of a raw pointer to make sure you don't leak memory, change your code to this - Also, since you are taking a string by value, consider wrapping it in your node class instance (you can also redirect it to a constructor
node
) - Prefers
nullptr
NULL in C ++ 11 and up
Copy 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;
}
source to share
#include <iostream>
using namespace std;
typedef struct node{
string city;
node * next;
} Node;
class Vertex{
public:
Vertex(string cityName) {
x = new Node();
x->city = cityName;
x->next = nullptr;
}
void printCity() {
cout << x->city << endl;
}
~Vertex(){
delete x;
}
private:
unique_ptr<Node> x;
};
int main() {
Vertex x("Phoenix");
x.printCity();
return 0;
}
source to share