suppose I have a structure.
struct node {
string info;
node link*;
}
what is the difference between
node k;
node b;
k.info = "string";
b.info = "string";
k.link = &b;
and
node *k;
node *b;
k = new node;
b = new node;
k->info = "string";
b->info = "string";
k->link = b;
in terms of memory allocation? Are both examples correct and create a proper linked list? Added: In most books the second example is used, why is that? Is there a down side to using the first example?
Yes. both are technically correct.
In the first example, the memory is on the stack, in the second on the heap.
When the memory is on the stack, the “compiler” is in charge of freeing the memory (when variables go out of scope). Since your linked list can outlive the variables you explicitly created, this can cause all sorts of problems. For example, in the first example, if
bgoes out of scope, butkdoesn’t, thenkwill have a dangling pointer, which leads to undefined behavior (aka bad).When the memory is on the heap, you have to manage the memory, which can cause problems if you forget to free it. This is harder then it sounds, considering exceptions. I suggest you use some form of a smart pointer. This is the most common and safest way to use a linked list.