singly linked list

May 29, 2015 at 1:50pm
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 May 29, 2015 at 1:54pm
May 29, 2015 at 1:56pm
Just because it isn't allocated doesn't mean it will crash, it just means that it will have undefined behaviour.
Last edited on May 29, 2015 at 1:56pm
May 29, 2015 at 2:01pm
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
May 29, 2015 at 2:09pm
@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.
May 29, 2015 at 2:38pm
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.
May 29, 2015 at 3:12pm

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
May 29, 2015 at 4:05pm
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 May 29, 2015 at 4:06pm
May 29, 2015 at 4:38pm
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 May 29, 2015 at 4:39pm
May 29, 2015 at 4:41pm
That code works fine, I don't think it does undefined behaviour.
Topic archived. No new replies allowed.