Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
i made a function to create a node in linked list which takes a integer as argument ,my program is running fine when i am using this function but my doubt is in malloc used here

What I have tried:

my structure is
struct{
int data;
struct node*}

this is my insert function
void insert(int x){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->next=head;
head=temp;

}

note i declared head as a global variable as
struct node* head;

clearly head is a pointer variable(pointer to struct node) which will take only 4 bytes
in memory whereas (struct node) will take 8 bytes in memory
my doubt is this when i am using head in sizeof operator instead of struct node that is
struct node *temp=(struct node*)malloc(sizeof(head));
i am getting no error
no warning and getting the exact answer as was before but memory allocation will be different for head(4bytes) and struct node(8 bytes) it should affect my program??
Posted
Updated 8-Jul-18 8:56am
v2

1 solution

Your structure will always be bigger than the pointer to it: if only because the actual node contains a pointer to the struct so it has to be at least the size of a pointer plus the size of the other elements.

So yes, you must use sizeof(struct node) when you malloc the node itself.
If you don't then yes you will get problems ... but you may not notice them in development depending on two factors: the packing of adjacent nodes, and the granularity of the malloc function, which is often not what you think: some systems will always allocate memory in multiples of an 8 or 16 byte chunk , so your code works ... until your compiler or it's options changes ... :laugh:

Always ask for the right size: never rely on "effects" to get you out of a hole!
 
Share this answer
 
v2
Comments
thakurcoder 9-Jul-18 0:07am    
thanks for assisting me i got it
OriginalGriff 9-Jul-18 1:30am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900