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;
}
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:
explicit function-specifier to your constructor to avoid accidental implicit conversion from string.Three more things
unique_ptr instead of a raw pointer to make sure you don't leak memory, change your code to thisnode)nullptr to NULL in C++11 and beyondChance 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With