-2

I'm trying to create a simple linked list and a variable t oread through it. However, I'm gettin a segfault in a place I didn't think would get one. Here's my code

    #include <iostream>
    #include <string>
    using namespace std;

    struct Node {
     string name;
     Node *next;
    };

    int main() {
     Node *one;
     one->name = "one";
     Node *two;
     two->name = "two";
     Node *three;
     three->name = "three";

     Node *reader = one;
     while (reader != NULL) {
      cout << reader->name << endl;
      reader = reader->next;
     }
    }

I added a few cout's around my code and realized that the segfault was happening after

    one->name = "one";

I'm not very experienced in C++, but I thought a segfault occurred when the stacks overflowed in memory. I don't see how the program should be running out of memory there. I'd appreciate any help in finding out the problem. Thanks.

Many Questions
  • 125
  • 1
  • 10
  • 2
    You never allocated memory for your `node*` pointers. – πάντα ῥεῖ Feb 19 '16 at 23:57
  • Yer need less stars, fewer arrers and moar dots. – Martin James Feb 20 '16 at 00:14
  • *I'm not very experienced in C++* -- Then it is a good idea to get a good C++ book and go through the examples, understanding everything as you go along. You're making a fundamental mistake that no good book would have illustrated. – PaulMcKenzie Feb 20 '16 at 00:15
  • Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Feb 20 '16 at 17:26

1 Answers1

2

You create a pointer to Node but you never create a Node-object.

Use

Node* one = new Node();

and don't forget delete one; at the end of your program.

Basically you have allocated memory for a pointer to Node, but the content is some random adress in memory. You need to actually create a Node-object and assign its adress to your pointer. If not, you are trying to dereference a random adress. (Compare it to writing int i; which will hold a random int if not initialized)

Anedar
  • 4,235
  • 1
  • 23
  • 41