bug-make
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Invalid use of const pointer?


From: Edward Welbourne
Subject: Re: Invalid use of const pointer?
Date: Tue, 11 Jan 2022 10:57:39 +0000

On Sat, 08 Jan 2022 17:29:33 -0500 Paul Smith <psmith@gnu.org> wrote:
>>> It turns out to be innocuous because none of the callers care that
>>> the value of the input string is modified if we return a different
>>> string, but it's still wrong and should be fixed.

Indeed.  The compiler is allowed to place a string literal in read-only
memory, where modifying it (even if you do "put it back the way it was"
later) is an access violation.  Passing such a const char * to your
function would thus crash.

On Sun, 2022-01-09 at 11:06 +0100, Henrik Carlqvist wrote:
>> If so, the easy and more correct fix might be to to remove const from
>> the function variable declarations rather than to restore the value.

Paul Smith (9 January 2022 16:17) wrote:
> It's not that easy.  Removing the const from the argument means that we
> have to change all the caller's types to remove const, and that means
> all the callers of those methods have to remove const, etc.

Yes, and those callers _should_ be declaring the pointer non-const,
since passing a pointer to read-only memory to them would lead to a
crash.  The type system is there to help you keep track of whether your
code is safe: any string that gets passed down to this function does
need to be in mutable memory.

> In any event, the bug still exists whether you say the argument is
> const or not: the expectation when this function is called is that
> after it returns the string passed to it has the same content as before
> it was called.

The failure to restore the string to its prior content is a separate bug
from the wrongly declared parameter type.

The C library's assorted functions taking a const char * and returning a
char * are a type violation in the standard.  They're needed because the
language doesn't allow for overloading, so can't declare the two forms
of each function that it needs (one taking and returning const char *,
the other taking and returning (mutable) char *); but it is A Bad Plan
to actually pass a const char * to one and use the return as anything
but const char *.  As noted above, a const char * could in fact be in
read-only memory.

        Eddy.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]