singly linked list

i just started reading about linked list and doing it from scratch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
  struct node
  {
      std::string name;
      node *next;
  };
   
  node *root;
  node *traverser;

  root = new node;

  root->name = "1";
  root->next->name = "2"; // why is this working? it should crash the program
                           // next node isnt allocated yet.
  
}

Last edited on
Just because it isn't allocated doesn't mean it will crash, it just means that it will have undefined behaviour.
Last edited on
but when i didnt allocate the root node, its crashing.


 it just means that it will have undefined behaviour. 

thanks, so i should i allocate it for safety
@shadowmouse

1
2
3
4
5
6
    root = new node;
    root->_test = "First Node";
    root->next = new node;
    root->next->_test = "Second Node";
    root->next->next = new node;
    root->next->next->_test = "Third Node";


why am i getting undefined behaviour here too? even though all node has been initialized properly.
Can you post full code including the above as firstly, it will allow me to run it in the cpp.sh shell, and secondly, you're first example doesn't have _test in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  
struct node
{
 std::string _test;
node *next;

};

    node *root;
    root = new node;
    root->_test = "First Node";
    root->next = new node;
    root->next->_test = "Second Node";
    root->next->next = new node;
    root->next->next->_test = "Third Node";

	


this is the full code
How can that be the full code when it doesn't even include int main()? I meant post full compilable code, which will show up as having a small cog icon on the top right when posted.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <iostream>
int main()
{
struct node
{
 std::string _test;
node *next;

};

    node *root;
    root = new node;
    root->_test = "First Node";
    root->next = new node;
    root->next->_test = "Second Node";
    root->next->next = new node;
    root->next->next->_test = "Third Node";
   
}
Last edited on
That code works fine, I don't think it does undefined behaviour.
Topic archived. No new replies allowed.