I am new to c programming language,

I have written this small code and I dont know why cant i use the free() here, any clarification highly appreciated.

int insert(element **head, int d)
        element *temp;

        temp = (element*)malloc(sizeof(element));

        if(temp == NULL)
                printf("\nError: Failure to allocate memory\n");

        temp->data = d;
        temp->next = *head;

        *head = temp;

        free(temp); // --->>> why ? cant i use free() here ?
        temp = NULL;
        return 1;

Also, could you give a small basic example of where free may be used.


You do not want to free temp there. Remember that you do not free pointer variables, but the memory that they point to. In this case, you do not want to free the memory that temp points to because you still have a pointer (*head) pointing to it and the memory is still being used.

free(xxx) is used when you actually want to delete the memory (often called the object) that the pointer points to.

This question has already been answered. Start a new discussion instead.