bawejakunal
bawejakunal

Reputation: 1708

Prevent double kfree in kernel code?

I am working on some system calls in the linux kernel. Since double kfree() raises an error, what could be a good safeguard against that ?

One obvious idea I had in mind was to set the pointer to NULL after kfree() and check if it's NULL before next possible kfree(). I am not sure if this is the right way to do so. Please guide me.

Upvotes: 0

Views: 1145

Answers (1)

Ezequiel Garcia
Ezequiel Garcia

Reputation: 1057

Usually, you want to avoid that situation by design. Few examples:

  • kmalloc() on your driver's .probe, and you kfree() on your driver's .remove. Then you are good, the probe/remove calls are balanced by the kernel.
  • kmalloc() on your char driver's .open, and you kfree() on your driver's .release. Also good, the open/release calls are balanced by the kernel.

However, in certain cases, where for some reason you just want to deallocate the object if it was allocated, then your approach of NULLifying the pointer and check before kfree() is perfectly fine. (I would say it's a trace of something poorly designed... but I've been there and done it ;)

In the future, when you have a question like this, where you want to see if an approach is popular enough, you can browse the kernel sources. Look for similar drivers and see what patterns are used. It will give you great insight!

Upvotes: 4

Related Questions