0
votes

Inside a function for linked list:

// nodePtr is a pointer to a struct
// list is a pointer to the linked list
nodePtr *current = list;

[some manipulation using *current here...]

// insert new node in front of *current node
nodePtr temp = *current;
*current = createNode(value);
(*current)->next = temp;

Because temp is not a direct pointer so when I assigned (*current)->next back to temp, will it creates a copy in the heap? And then the original memory now has no pointer to it and leaked?

I was trying to setup an insert function for a linked list that insert the node in order (a member in struct to check the value) so it requires no sorting.

3
Oh, this code is misleading. Please don't hide pointer types behind typedefs!Oliver Charlesworth

3 Answers

0
votes

will it creates a copy in the heap?

When you assign one pointer to another, no additional memory is allocated on the heap.

0
votes

If nodePtr is a pointer to a struct(I assume you typedef nodePtr), then you have defined current as a pointer to pointer to a struct. Current has to be initialised with a pointer to type nodePtr not a pointer to the struct.

nodePtr current = list //this should work
0
votes
nodePtr temp;

This line assigns memory for 'temp' variable in stack(not heap). It is just a pointer variable which can store address of a structure which you have typedef'd somewhere.

Also, there will be no leakage in this code. You, perhaps, allocated memory for creating new node and it is getting stored in (*current)->next.

As nodePtr is already a pointer type, current is a double pointer. So I think, this is incompatible

nodePtr *current = list;

It should be something like

nodePtr *current = &list;