Why driver programming prefer kzalloc over kmalloc

10,036

Solution 1

It depends on the definition of relevant content.

If you do not care about the content of the memory you can just usekmalloc; this is the case of buffer allocation, you do not care about the initial content because you are going to write your data. In this case you save the 'cost' of setting the memory to 0.

But things are different if you are going to allocate memory for a structure. Personally, I prefer kzalloc only when I want to allocate structures where I'm going to set some value (different than 0) but at the same time I want to set all the other fields of the structure to a known and valid state (zero). For example:

struct test {
    int counter;
    void *buffer;
    int n_data;
};

In this case if I would use kzalloc I will save some line of code because:

  • initialize a counter to 0 at the beginning, usually, it is a nice thing to do;
  • set to NULL the buffer it is also fine because I will allocate it later and by setting it to NULL I can simply write the following because it is a known state:

    if (!t->buffer)
        t->buffer = kmalloc(10);
    
  • setting the number of data n_data to zero is good because the buffer at the beginning is empty and not allocated.

Of course, if in your structure you are going to set manually most of the fields with a value different than zero, then it make less sense (at least for me) to initialize everything to zero with kzalloc

Solution 2

Well. This is not very speicific to Linux Kernel and kmalloc/kzalloc as such. But its general problem around allocating and using the memory.

These guys have covered many cases of what could happen if you just do allocation and not zero it out. And these are still user-level stuff, imagine this things happening in Kernel.

Refer: zeroing out memory

Share:
10,036

Related videos on Youtube

Jaydeep Sen
Author by

Jaydeep Sen

Updated on October 24, 2022

Comments

  • Jaydeep Sen
    Jaydeep Sen over 1 year

    AM I correct to observe that in case of any memory allocation done within device driver routines, kzalloc is preferred over kmalloc ?

    I have seen kernel patches replacing kmalloc+memset with kzalloc. But my doubt is why one needs to set memory content at all ? Why can't we just use kmalloc when the memory is later expected to get written with relevant content anyway ?