why malloc for a new node in linked list 
Author Message
 why malloc for a new node in linked list

hi there,

i'm new to c and i was wondering why do i need to reserve memory for a
new node when moving one (node)

assuming i have a struct like:

struct Test {
    int data;
    struct Test *link;
    }

i traverse the list and see that Test->link == NULL. fine, so i make a
new node. why then, do i see
malloc in my example code. why ? the pointer already has been declared,
it only has to be initiated. right ?
the pointer just points, not stores.

i think malloc gives a pointer back to  where it allocated the memory
block. but i don't get why it needs to
allocate memory...



Sun, 11 Jul 2004 14:44:17 GMT  
 why malloc for a new node in linked list

Quote:

> hi there,

> i'm new to c and i was wondering why do i need to reserve memory for a
> new node when moving one (node)

> assuming i have a struct like:

> struct Test {
>     int data;
>     struct Test *link;
>     }

> i traverse the list and see that Test->link == NULL. fine, so i make a
> new node. why then, do i see
> malloc in my example code. why ? the pointer already has been declared,
> it only has to be initiated. right ?
> the pointer just points, not stores.

> i think malloc gives a pointer back to  where it allocated the memory
> block. but i don't get why it needs to
> allocate memory...

But if you don't call malloc, what is the pointer going to point to?

--
Stephen Montgomery-Smith

http://www.math.missouri.edu/~stephen



Sun, 11 Jul 2004 05:49:36 GMT  
 why malloc for a new node in linked list

Quote:
> i'm new to c and i was wondering why do i need to reserve memory for a
> new node when moving one (node)

Well, I personnally see a contradiction between "being new to C" and
"linked list". Let's go anyway.

Quote:
> assuming i have a struct like:

> struct Test {
>     int data;
>     struct Test *link;
>     }

The creation of a new node is not spontaneous. A node is nothing but a
structure with a certain size (exactly sizeof(struct Test) in your case).
So if you want to add a new node to the list, you must create it first.
There are probably other methods, by the most popular is an malloc() or
the required size. (Keep in mind that malloc() can fail. In this case, it
returs NULL).

Quote:
> i traverse the list and see that Test->link == NULL. fine, so i make a
> new node. why then, do i see
> malloc in my example code. why ? the pointer already has been declared,

Test->link is defined and it's value is NULL. It means that there is no
else element in the list.

Quote:
> it only has to be initiated. right ?
> the pointer just points, not stores.

A pointer does store, of course. This confirm my first impression that
linked lists are a bit a difficult concept for a new programmer. Let's do
it from the beginning.

- A pointer is a variable designed to yeld the address of an object.
- When defined, it's not initialized (in most cases).
- There are a few portable ways of assigning a pointer:
  - assign the null pointer constant (aka 0 or NULL)
  - assign the address of an object
  - assign the value returned my malloc() (and brothers)
  - assign the value returned my fopen() (only for FILE* pointers)
  - assign the value of another pointer (or pointer expression)
    of the same type
  - assign the value of another pointer (or pointer expression)
    of any type if its type is void*.
  - assign the value of another pointer (or pointer expression)
    of type void*
(I may have forgot some, correction welcome)

Some example:

   char *pa = 0;
   char *pb = NULL;
   char a;
   char *pc = &a;
   char *pd = malloc (10); /* <stdlib.h> */
   FILE *pe = fopen ("yadayada","r"); /* <stdio.h> */
   char *pf = pd + 1;
   void *pg = pd;
   char *ph = pg + 4;

Quote:
> i think malloc gives a pointer back to  where it allocated the memory
> block. but i don't get why it needs to
> allocate memory...

To create a new node. Once you have its address, you can 'link' it with
the list:

(kinda pseudo-code)

{
   /* allocates a new node */
   struct Test *pnew = malloc (sizeof *pnew);

   /* success ?*/  
   if (pnew != NULL)
   {
      /* add the new node at the end of the list */
      pTest->link = pnew;

      /* mark the new end of the list: VERY important */
      pTest->link->link = NULL;
   }

Quote:
}

Got it?

--
-ed- emdel at noos.fr
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-library: http://www.dinkumware.com/htm_cl/index.html
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/



Sun, 11 Jul 2004 06:39:53 GMT  
 why malloc for a new node in linked list


Quote:
> hi there,

> i'm new to c and i was wondering why do i need to reserve
> memory for a new node when moving one (node)

> assuming i have a struct like:

> struct Test {
>     int data;
>     struct Test *link;
>     }

> i traverse the list and see that Test->link == NULL.

You see that p->link == NULL, where p is a pointer to struct
Test.

Quote:
> fine,
> so i make a new node. why then, do i see
> malloc in my example code. why ? the pointer already has
> been declared, it only has to be initiated. right ?

You are right. It needs to be initiated to point to something
valid. You can do many things:

p->link = &t;  /* t is a variable of type (struct Test) */
p->link = q ;  /* q is variable of type (struct Test*) */
p->link = malloc(sizeof struct Test); /* Create a new node */

The only thing you care is it should point to something where
you can store data. Not necessarily a malloc'd one.

Dynamic allocation is used so that you can create nodes as and
when you need them, and you can get rid of it when you no
longer need them....

Hope this helps.

- Umesh

--

Umesh P Nair
Remove 'z's from my e-mail ID



Sun, 11 Jul 2004 13:13:32 GMT  
 why malloc for a new node in linked list
Although p->link = &t is legal, you probably want to pass pointer p into
other functions.
Therefore p->link = malloc(sizeof struct Test) is better because it is
guarunteed that memory will be accessable if
the pointer is being used in a local context or as a return value from
another function.
i.e
/* wrong way */
struct Test* init (void);
{
    struct Test p;
    p.link=NULL;
    return &p;  /* legal but memory is only allocated in this context */
Quote:
}

.....
struct Test *p;
p=init();
p->data=... /* might crash because buffer would have been freed after return
in init function */
......
/* right way */
struct Test* init (void);
{
    struct Test *p;
    p=malloc (sizeof (struct Test));
    if (p) /* always check malloc results */
    {
         p->link=NULL;
         return &p;
    }
    else
    {
       .... error stuff .....
    }
Quote:
}

.....
struct Test *p;
p=init();
if (p)
{
   p->link=... /* buffer is good! */
Quote:
}

......
Hope this helps! Learn all of the intricacies of malloc, it will save you
greif later!


Sun, 11 Jul 2004 15:27:12 GMT  
 why malloc for a new node in linked list
Thanks everyone.

I had it figured out once i read the man page for malloc and thinking about it
for a bit.
malloc returns a pointer to the allocated memory and thus the pointer gets
initiated.

I was thinking with the wrong mindset, seems to happen a lot. Most questions i
post
though get me so frustrated i solve them myself in maximum a day ;-)

Quote:

> Although p->link = &t is legal, you probably want to pass pointer p into
> other functions.
> Therefore p->link = malloc(sizeof struct Test) is better because it is
> guarunteed that memory will be accessable if
> the pointer is being used in a local context or as a return value from
> another function.
> i.e
> /* wrong way */
> struct Test* init (void);
> {
>     struct Test p;
>     p.link=NULL;
>     return &p;  /* legal but memory is only allocated in this context */
> }
> .....
> struct Test *p;
> p=init();
> p->data=... /* might crash because buffer would have been freed after return
> in init function */
> ......
> /* right way */
> struct Test* init (void);
> {
>     struct Test *p;
>     p=malloc (sizeof (struct Test));
>     if (p) /* always check malloc results */
>     {
>          p->link=NULL;
>          return &p;
>     }
>     else
>     {
>        .... error stuff .....
>     }
> }
> .....
> struct Test *p;
> p=init();
> if (p)
> {
>    p->link=... /* buffer is good! */
> }
> ......
> Hope this helps! Learn all of the intricacies of malloc, it will save you
> greif later!



Mon, 12 Jul 2004 13:17:03 GMT  
 why malloc for a new node in linked list
I do wonder though, are these kind of mechanisms still used ? Like, how would
they be used.
as an inventory system in a game ? and then wat, put a item in every link or...

just wondering what it's good for, or if it's still implemented.

also, isn't a binary tree almost the same thing ?

Quote:

> Although p->link = &t is legal, you probably want to pass pointer p into
> other functions.
> Therefore p->link = malloc(sizeof struct Test) is better because it is
> guarunteed that memory will be accessable if

> the pointer is being used in a local context or as a return value from
> another function.
> i.e
> /* wrong way */
> struct Test* init (void);
> {
>     struct Test p;
>     p.link=NULL;
>     return &p;  /* legal but memory is only allocated in this context */
> }
> .....
> struct Test *p;
> p=init();
> p->data=... /* might crash because buffer would have been freed after return
> in init function */
> ......
> /* right way */
> struct Test* init (void);
> {
>     struct Test *p;
>     p=malloc (sizeof (struct Test));
>     if (p) /* always check malloc results */
>     {
>          p->link=NULL;
>          return &p;
>     }
>     else
>     {
>        .... error stuff .....
>     }
> }
> .....
> struct Test *p;
> p=init();
> if (p)
> {
>    p->link=... /* buffer is good! */
> }
> ......
> Hope this helps! Learn all of the intricacies of malloc, it will save you
> greif later!



Mon, 12 Jul 2004 13:18:26 GMT  
 why malloc for a new node in linked list

Quote:

> I do wonder though, are these kind of mechanisms still used ? Like, how would
> they be used.
> as an inventory system in a game ? and then wat, put a item in every link or...

> just wondering what it's good for, or if it's still implemented.

> also, isn't a binary tree almost the same thing ?

Definitely, you these data structures appear everywhere! Memory
management schemes, caching schemes, file systems, etc. Its just too
many to mention.

The difference between a link list and a binary tree is search time. A
link list can be searched linearly. Lets say you have linked list and
the 50th element is x. You pass that link list and you need to find x.
It takes 50 iterations! A binary tree on the otherhand is not linear.
You can add nodes in any order specified by your algorithm. This could
lead to faster search times.

My 50 node link list example may not sound too bad but if you have to
constantly search the link list or if the list is very long like a
file system (perhaps) you can get horrible performance times. AI
algorithms may use binary trees to search for solutions; these data
structures are everywhere!

A binary tree can degrade into a linear list under certain conditions.
-- Mark



Mon, 12 Jul 2004 12:54:55 GMT  
 why malloc for a new node in linked list

Quote:

> I was thinking with the wrong mindset, seems to happen a lot. Most
> questions i post
> though get me so frustrated i solve them myself in maximum a day ;-)

Congratulations on getting it - I have known many people trip up,
permanently, on the pointer concept.

Joel Spolsky (http://www.joelonsoftware.com) has suggested that pointers
and pointer arithmetic are responsible for the high rate of dropout in CS
courses at the time of their introduction. :-)

--
Duncan Bayne


     - Web    http://homepages.ihug.co.nz/~dhbayne/
     - Cell   (+64) (0)25 626 3023

Once a word has been allowed to escape, it cannot be recalled.
                -- Quintus Horatius Flaccus (Horace)



Tue, 13 Jul 2004 10:47:03 GMT  
 
 [ 9 post ] 

 Relevant Pages 

1. Linked List -- why not just "malloc()"?

2. nodes linked listed and such

3. 2 nodes end up in a cycle in a single linked list

4. newbie question: removal of node in linked list

5. How to find a node in link list

6. Realloc()ing data of a node from a linked list

7. Destroying All Nodes in a Linked List

8. Destroying All Nodes is a Linked List

9. Removing node from linked list

10. Removing a NODE for good (double linked lists)

11. deleting a previous node in a singly linked list

12. Question about swapping nodes in a doubly linked list

 

 
Powered by phpBB® Forum Software