I have following method in the c code.
void add(int number)
{
Node node1; // a new node should be created
createNodeRelationshipBetween(&node1, current);
setData(&node1, number);
setCurrentNode(&node1);
incrementSize();
printf("Inserted Node [data:- %d, Node address:- %p\n", node1.data, &node1);
}
where Node is defined as
typedef struct node
{
struct node *prior;
struct node *next;
int data;
} Node;
I am calling add() in a loop. My understanding is that every time i call add(i), a new Node should be created. Instead when i print the address of node1, it is same every time. Can someone please explain where the error is and how do i create a new node?
Your function does create a new
Node, but only as a local variable. When youradd()function returns, it vanishes. If you’re callingadd()in a loop, the address of theNodeobject on the stack is always going to be the same.To make your new
Nodepersistent, you will need to allocate some persistent memory for it – check outmalloc(3)andfree(3). A quick example:You will need to keep track of the
node1pointer so as not to introduce a memory leak. You can usefree(3)later to destroy the allocation.