On Sunday, November 21, 2021, Harald van Dijk <har...@gigawatt.nl> wrote:
> On 21/11/2021 07:12, Kang-Che Sung wrote:
>>
>> On Sunday, November 21, 2021, David Laight <david.lai...@aculab.com
<mailto:david.lai...@aculab.com>> wrote:
>>  >
>>  > You shouldn't need the strdup().
>>  > I think you can even do:
>>  >         if (!(opt & 1))
>>  >                 prompt = "";
>>  > because (IIRC and for historic reasons) quoted strings are char[] not
const char[].
>>
>> I don't know why you are messing up with the "constness" of the strings.
C standard says string literal is of type const char[], and the const
keyword didn't exist before C89.
>> Note the compiler is free to merge string literals with identical
content so they share the same buffer in the .rodata section (that's why
they are const).
>
> It does not say that, it says the opposite:
>
>   The multibyte character sequence is then used to initialize an array
>   of static storage duration and length just sufficient to contain the
>   sequence. For character string literals, the array elements have type
>   char, and are initialized with the individual bytes of the multibyte
>   character sequence.
>
> Note the "char" as opposed to "const char".

It refers to the initialization like this:

   char str[] = "abc";
   str[0] = 'd'; // Vaild

not this:

   char arr[5];
   arr = "abc";
   arr[0] = 'd'; // Undefined behavior

nor this:

   char *ptr;
   ptr = "abc";
   *ptr = 'd'; // Undefined behavior

And messing with the "constness" is always a bad idea.

The compiler actually treats the string literals of the latter two examples
to have the type 'const char[]', so modifying the contents yields undefined
behavior, matching what the standard says.
_______________________________________________
busybox mailing list
busybox@busybox.net
http://lists.busybox.net/mailman/listinfo/busybox

Reply via email to