Linkedlist and memory addresses

I have a question concering pointers, memory and creating listnodes:

I have the following structure:

    typedef struct node {
       int data;
       struct node *next;
    } node;

And create a (new) node with the following function

 static node *createNewNode(int data) {

    node *nodePtr = queuer.lastNode;
    if (queuer.lastNode == NULL) {
        nodePtr = malloc(sizeof(*nodePtr));
        nodePtr->data = data;
    } else {
        nodePtr->next = malloc(sizeof(*nodePtr));
        nodePtr = nodePtr->next;
        nodePtr->data = data;
    }
    return nodePtr;
}  

So In every new node I put an integer. After creating the new node I print the stored integer and it seems ok (though I have not looped the linked list yet). But I also print the pointers and I do not Understand why It look like this:

printing nodePtr

 printf("data: %d", nodePtr);

and the output is as follows if I create six nodes:

205888

206032

216056

216072

216088

216104

and I do not understand why the jump in memoryaddress is so big bewteen the two first nodes, that is the difference is 144. After that the difference is constant, that is 16

So my question is: Is this normal or am I doing something wrong in the code?

Edit to the post: I've made another function that prints the linked-list and everything seems fine.

Upvotes: 0

Views: 1151

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54355

The answer to why the address values change like that is complicated. The malloc function is probably using an extra 8 bytes per malloc to record the size of the allocation and a pointer to the next block. The 144 byte jump is probably because another malloc block was in the way.

Upvotes: 1

Jekyll
Jekyll

Reputation: 1434

I see an error there, when you add a node you should do this:

nodePtr = nodePtr->next;
nodePtr->data = data;
nodePtr->next = NULL;

adding nodePtr->next = NULL will you permit to traverse the list if you don't know how many elements it contain.

Apart from this there is nothing wrong as you cannot predict where the node will be created in the heap. You probably allocated something after the head node and before adding other nodes.

Upvotes: 1

Related Questions