开发者

Why is new Node not being created?

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开发者_JS百科);
    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?


That code is creating a Node structure on the stack. As soon as you leave the function that node is destroyed. The pointer is the same because it is pointing to the same local variable on the stack each time. The solution is to allocate space on the heap for the variable with something like malloc:

malloc( sizeof( Node ) )

You can then use the returned pointer in the way you have. Don't forget to free the nodes when you're done.


Your function does create a new Node, but only as a local variable. When your add() function returns, it vanishes. If you're calling add() in a loop, the address of the Node object on the stack is always going to be the same.

To make your new Node persistent, you will need to allocate some persistent memory for it - check out malloc(3) and free(3). A quick example:

Node *node1 = malloc(sizeof(Node));

You will need to keep track of the node1 pointer so as not to introduce a memory leak. You can use free(3) later to destroy the allocation.


node1 is a local variable, so it gets recreated on every call to the function, and destroyed on every return.


node1 is local to your add function - if you want it to persist outside of that function, then allocate off the heap using malloc


A new Node is not created by the line Node node1;. This line merely declares a variable whose scope is limited to the lifetime of the function (that is, the variable is placed on the stack). When the function returns, node1 no longer exists.

Since you are calling add() in a tight loop, what is probably happening is that each call to add() is getting assigned the same stack range and node1 just happens to have the same address every time the function is called.

If each invocation of add() needs to have a unique node1 with a unique address, then you will want to dynamically allocate the object with malloc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜