Search code examples
cpointersdynamic-memory-allocation

Inserting a value in linked list


This is not really a problem but a small doubt.
I was creating a function to insert a key value in a linked list.

void Insert_val(ListNode **l , int x)//to insert value of x;
{
    ListNode *p ;//create a pointer to datatype ListNode
    p = malloc(sizeof(ListNode));//give pointer chunk from memory to store data
    p->val = x;//value of p is x
    p->next = *l;// next ptr of p points to 1st node
    *l = p;//head ptr of list points to p making it first node
}

After allocating memory to a pointer how it divides memory into two parts that contain value x and next pointer?
How does p pointer do that pointer p just points to a datatype of type ListNode when given a random chunk of memory, how it divides it so that it make the required datatype?


Solution

  • Your phrasing "allocating memory to a pointer" does not really describe what is happening. You do not have a pointer to which memory is allocated.

    I consider it the reverse. malloc() finds some memory of the desired size which is free for you to use. It returns the address to you and makes a note that this memory is now used and e.g. cannot be used next time you call malloc(). You then write that value (the address) into your pointer variable, I would phrase that as "your code after the malloc call assigns the returned address to the pointer variable", while malloc itself is unaware of that pointer.

    It is not part of malloc() to "divides memory into two parts that contain value x and next pointer". That is you doing it; though probably unaware and indirectly by telling the compiler that the allocated memory is now used with a structure as defined by the struct-type you are using for "what p points to".

    The compiler simply trusts you that "p just points to a datatype of type ListNode when given a random chunk of memory", because your code says so. Your responsibility, your risk. Because many many pointer/malloc-related problems come from that responsibility being not really covered by the programmer in question.

    I recommend to find a book for learning about these issues, maybe a tutorial.