About allocating memory to a node in a link list

K

Kane

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
 
E

Eric Sosman

Kane said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top