struct student


  int roll_no;

  int mark;

  struct student *p;

} ;

int main()


  struct student *stu;

  stu=malloc(sizeof(struct student));


What is the actual return value of an malloc() for a

structure type? How it is being assigned to the

structure variable?

Now for the statement ,

Struct student *stu;

Memory allocation be like this

roll_no: 1000 - 1004

mark: 1004 - 1008

p: 1008 - 1012

And for the statement

stu=malloc(sizeof(struct student));

My assumptions are as follow

First Allocates block of memory

Let's just say 2000 - 2012

Then the assignment part

2000 stored at 1000

2004 stored at 1004

2008 stored at 1008

Is this how the assignment part works for malloc()

and structure variable or do we have anyother


2 Answers

JL2210 On

malloc() returns a pointer to a block of memory (void *) large enough to hold size (first argument) bytes regardless of what the argument is or what the result is being casted to.

For example, stu->roll_no would access the first two bytes (assuming int is 32-bit) of the allocated memory (assuming that the structure is not padded).

In C, void * pointers are implicitly converted into the pointer type of what they are assigned to.

Praveen Kumar Karthikeyan On

Please make corrections if there is any mistake in my understanding, so for the statement, struct student *stu; 4 bytes of memory space is allocated for the next statement stu=malloc(sizeof(struct student)); first block of memory is allocated let's just say some 12 bytes are allocated and the starting address to that block is assigned to stu. Therefore if we say stu->roll_no first 4 bytes are accessed and if we say stu->marks the next 4 bytes will be accessed. And if we say stu->p the next 4 bytes are accessed. And for clarity sake, unlike a normal structure variable which will allocate 12 bytes for the struct student whereas a structure pointer variable allocates just 4 bytes.