By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,836 Members | 1,725 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,836 IT Pros & Developers. It's quick & easy.

About allocating memory to a node in a link list

P: n/a
When you create node 1 you allocate memory and link it Again when you
create node 2 you would allocate memory for that node in a different
section of the code. Is there more efficient way where I can allocate
memory once and use it to create new node in list.
-Thanks
-Kane
Nov 13 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Kane wrote:

When you create node 1 you allocate memory and link it Again when you
create node 2 you would allocate memory for that node in a different
section of the code. Is there more efficient way where I can allocate
memory once and use it to create new node in list.


I'm not sure what you're asking, but I'll make
an attempt at answering anyhow ...

If the linked list has two nodes, those two nodes
must occupy two chunks of memory. Three nodes require
three chunks, N nodes require N chunks. You might be
able to play strange games by having the various chunks
overlap each other partially, but that way lies madness.

The existence of two or three or N chunks doesn't
necessarily imply two or three or N separate allocations.
You could, for example, use malloc() to reserve enough
memory for twenty nodes and then dole them out one by
one internally; this technique has some advantages when
the nodes are very small and very numerous. However, you
cannot then free() or realloc() the individual nodes;
you can only use free() or realloc() on the original
twenty-node block as a whole.

The existence of multiple allocated blocks (whether
of one or many nodes each) doesn't imply the presence
of multiple malloc() calls in your code. You can (and
usually should) arrange to execute and re-execute and
re-re-execute a single malloc() call as many times as
needed. Sometimes it's convenient to treat the very
first node specially and use an executed-only-once
malloc() call for it, but you should almost always have
just a single malloc() for every subsequent block.

If that doesn't answer your question, try restating
it more clearly.

--
Er*********@sun.com
Nov 13 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.