Freeing Volatile Pointer

Peter Pentchev roam at ringlet.net
Mon Jan 3 12:53:48 GMT 2005


On Mon, Jan 03, 2005 at 06:09:45PM +0530, Tejas Sumant wrote:
> Hi,
> 
> I have a volatile pointer declared in my device driver.
> I am allocating memory using kernel malloc function.
> 
> host_mem_resp_ptr = (volatile unsigned long *)malloc(sizeof(volatile
> unsigned long), M_DEVBUF, M_NOWAIT);
> 
> When I try to free it, I get following warning while compiling the driver.
> 
> "warning: passing arg 1 of free discards qualifiers from pointer target
> type"
> 
> The statment to free the memory is
> 
> free(host_mem_resp_ptr, M_DEVBUF);
> 
> Can anybody please tell me reason and solution?

The reason is that the C compiler treats 'void *' and 'volatile void *'
as different types.  In this case, the compiler casts your 'unsigned long *'
to 'void *' and still warns you that this might not necessarily be what
you want, although it is harmless in this case.

In theory, if a function is declared as accepting a non-volatile pointer,
passing a volatile pointer could be dangerous - the function could stash it
somewhere and then attempt to reuse it later when its value has actually
been changed.  This might cause the function to access memory that is no
longer allocated, or just the wrong chunk of memory, or something similar.

In your case the only danger lies in some other thread modifying the
pointer *and invalidating the memory* that it previously pointed to,
after you call free() and before free() has actually freed the memory.
It is up to you to decide whether this is a risk - or rather, to make
sure that it isn't :)  Then use something like:

   free((void *)host_mem_resp_ptr, M_DEVBUF)

...and you should be okay, unless you specifically pass -Wcast-qual to
the compiler.  If you do, it will again give this warning, just because
you have explicitly asked it to :)

G'luck,
Peter

-- 
Peter Pentchev	roam at ringlet.net    roam at cnsys.bg    roam at FreeBSD.org
PGP key:	http://people.FreeBSD.org/~roam/roam.key.asc
Key fingerprint	FDBA FD79 C26F 3C51 C95E  DF9E ED18 B68D 1619 4553
What would this sentence be like if pi were 3?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 187 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-hackers/attachments/20050103/180a26e3/attachment.bin


More information about the freebsd-hackers mailing list