Home > database >  What will happen if I malloc a pointer of a struct datatype which contains an element of a pointer o
What will happen if I malloc a pointer of a struct datatype which contains an element of a pointer o

Time:01-09

Consider the following code:

typedef struct list_ele
{
    char *value;
    struct list_ele *next;
}list_ele_t;

typedef struct
{
    list_ele_t *head;
    int qSize;
}queue_t;

And If I use a function to malloc a pointer of queue_t like this

queue_t *q = malloc(sizeof(queue_t));

What it actually happen? I mean, how big the memory it will create by malloc, should I use the following code

q->head = malloc(sizeof(list_ele_t));

to apply for space for q->head?

I'm not good at C language (;w;) , I try my best to think but I got nothing.

CodePudding user response:

A C pointer is usually!!! 8 bytes so when you do

queue_t *q = malloc(sizeof(queue_t));

you allocate 8(pointer) 4(int) 4(padding, see bellow) (usually) bytes of memory and you have q point to it. q->head is going to point to a random location as you have not assigned anything to it. Of course when you do

q->head = malloc(sizeof(list_ele_t));

you allocate 8 8 (usually) bytes of memory and you point q->head to it. Also learn what structure padding is:

sizeof(queue_t)    -> 16
sizeof(list_ele_t) -> 16

So you actually allocate more than 12 bytes for the memory that q points to.

CodePudding user response:

    Stack         |       Heap
                  |
      q ----------|--->  ------------ 
                  |       A chunk of           
                  |         memory    
                  |        equal to   
                  |         sizeof    
                  |         queue_t   
(a pointer to     |      ------------ 
 a struct of      |          / \
 type queue_t)    |         /   \ 
                  |        /     \  
                  |   qsize      head    
                  |                |
                  |                |
                  |                | 
                  |       -----------          
                  |        Chunk of   
                  |        memory of  
                  |        size list  
                  |       ----------- 
                  |

Side Notes:

  1. The storage that is allocated through malloc is uninitialized.

  2. malloc indicates failure by returning a NULL pointer value.

  3. For every allocation, there must be a free.

  • Related