[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20221112074759.GA5111@1wt.eu>
Date: Sat, 12 Nov 2022 08:47:59 +0100
From: Willy Tarreau <w@....eu>
To: A <amit234234234234@...il.com>
Cc: linux-kernel@...r.kernel.org
Subject: Re: Setting variable NULL after freeing it.
On Sat, Nov 12, 2022 at 11:47:39AM +0530, A wrote:
> Hi,
>
> I am writing a linux kernel driver for a new device.
>
> Is it a good practice to set variable NULL after freeing it?
>
> Something like this -
>
> kfree(x);
> x = NULL;
>
> Please let me know.
It depends. What's important is not to let a pointer exist to a freed
location, so if you're doing:
kfree(card->pool);
then it's usually important to follow this by:
card->pool = NULL;
so that no code stumbles upon that rotten pointer. Similarly if you're
freeing a variable in the middle of a function or inside an "if" block,
it's wise to reset the pointer so that it doesn't continue to exist
further in the function, and is visually easier to track for anyone
reviewing that code.
But a lot of kfree() calls exist in return paths and are only followed by
other kfree() and a return statement. In this case, it can be completely
useless to NULL a local variable that was just freed as the variable
stops existing when returning. For example, below nullifying the pointers
wouldn't bring anything:
kfree(card->pool);
kfree(card);
return -EBUSY;
A good way to check common practices is to check with git grep how
current code already deals with this:
$ git grep -wA3 kfree
You'll notice that all practices indeed exist.
Willy
PS: you could more easily get responses in the future by associating a
real name with your address instead of just "A" which makes it look
like a spam.
Powered by blists - more mailing lists