lkml.org 
[lkml]   [2020]   [Jun]   [27]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
From
SubjectRE: Writing to a const pointer: is this supposed to happen?
Date
From: Kars Mulder
> Sent: 24 June 2020 16:26
> On Wednesday, June 24, 2020 15:10 CEST, Greg Kroah-Hartman wrote:
> > Have you hit any runtime issues with this code doing this? These
> > strings should be held in writable memory, right? Or do you see a
> > codepath where that is not the case?
>
> I haven't ran into any issues with it; I was just looking at the code
> as reference for a patch I'm working on.
>
> I initially assumed that casting a const pointer to non-const and
> writing to it would be undefined behaviour, but after reading through
> the C99 standard I can't find an unambiguous statement whether it is
> undefined behaviour even if the const pointer points to an object that
> was originally non-const (like char* -> const char* -> char* casts); it
> only says it is undefined behaviour if the object was defined with the
> const qualifier.
>
> I should probably stop bothering you with my newbie questions.

IISC The C standard 'rules' about casts only really allow a pointer to
be temporarily cast to a different type and then cast back to the
original type before being used.

One effect of that is code like:
void foo(bah_t *bahp)
{
bah_t bah;
/* Copy because bahp might be misaligned */
memcpy(&bah, (void *)bahp, sizeof bah);
doesn't work because the compiler knows that 'bahp' must
point to aligned memory - because that is the only place
it can legitimately come from.
No amount of casts will stop it inlining memcpy() and using
wide register copier.

The code quoted (using strset()) is almost certainly wrong.
The caller is unlikely to expect the input be modified.
Since it doesn't fault the string must be in read-write memory.

Code can be compiled with -Wcast-qual that will generate a
warning when 'const' gets cast away.
There are some legitimate reasons to remove 'const', but not
many.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)
\
 
 \ /
  Last update: 2020-06-27 12:25    [W:1.109 / U:0.108 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site