11

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 ?

Jaydeep Sen
  • 111
  • 1
  • 1
  • 5
  • What if you forget to write the memory and read it. Or what if you read the non-zeroed memory before you write it? – Milind Dumbare Feb 20 '15 at 17:09
  • @Milind Dumbare those cases are considered bugs and as such they're out of scope of the problem. – Eric Aug 07 '20 at 15:06

2 Answers2

6

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

Federico
  • 3,782
  • 32
  • 46
4

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

Community
  • 1
  • 1
Milind Dumbare
  • 3,104
  • 2
  • 19
  • 32