Struct vs string literals? Read only vs read-write? [duplicate] - c

This question already has answers here:
Why are compound literals in C modifiable
(2 answers)
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 4 years ago.
Does the C99 standard permit writing to compound literals (structs)? It seems it doesn't provide writing to literal strings. I ask about this because it says in C Programming: A Modern Approach, 2nd Edition on Page 406.
Q. Allowing a pointer to a compound literal would seem to make it possible to modify the literal. Is that the case?
A. Yes. Compound literals are lvalues that can be modified.
But, I don't quite get how that works, and how that works with string literals which you certainly can't modify.
char *foo = "foo bar";
struct bar { char *a; int g; };
struct bar *baz = &(struct bar){.a = "foo bar", .g = 5};
int main () {
// Segfaults
// (baz->a)[0] = 'X';
// printf( "%s", baz->a );
// Segfaults
// foo[0] = 'a';
// printf("%s", foo);
baz->g = 9;
printf("%d", baz->g);
return 0;
}
You can see on my list of things that segfault, writing to baz->a causes a segfault. But, writing to baz->g does not. Why is that one of them would cause a segfault and not the other one? How are struct-literals different from string-literals? Why would struct-literals not also be put into read-only section of memory and is the behavior defined or undefined for both of these (standards question)?

First thing first: your struct literal has a pointer member initialized to a string literal. The members of the struct itself are writeable, including the pointer member. It is only the content of the string literal that is not writeable.
String literals were part of the language since the beginning, while struct literals (officially known as compound literals) are a relatively recent addition, as of C99. By that time many implementations existed that placed string literals in read-only memory, especially on embedded systems with tiny amounts of RAM. By then designers of the standard had a choice of requiring string literals to be moved to a writeable location, allowing struct literals to be read-only, or leaving things as-is. None of the three solutions was ideal, so it looks like they went on the path of least resistance, and left everything the way it is.
Does the C99 standard permit writing to compound literals (structs)?
C99 standard does not explicitly prohibit writing to data objects initialized with compound literals. This is different from string literals, whose modification is considered undefined behavior by the standard.

The standard essentially defines the same characteristics to string literals and to compound literals with a const-qualified type used outside the body of a function.
Lifetime
String literals: Always static.
§6.4.5p6 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.
Compound literals: Automatic if used inside a function body, otherwise static.
§6.5.2.5p5 The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.
Possibly shared
Both string literals and const-qualified compound literals might be shared. You should be prepared for the possibility but cannot rely on it happening.
§6.4.5p7 It is unspecified whether [the arrays created for the string literals] are distinct provided their elements have the appropriate values.
§6.5.2.5p7 String literals, and compound literals with const-qualified types, need not designate distinct objects.
Mutability
Modifying either a string literal or a const-qualified compound literal is undefined behaviour. Indeed attempting to modify any const-qualified object is undefined behaviour, although the wording of the standard is probably subject to hair-splitting.
§6.4.5p7 If the program attempts to modify [the array containing a string literal], the behavior is undefined.
§6.7.3p6 If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
A non-const-qualified compound literal can be freely modified. I don't have a quote for this, but the fact that modification is not explicitly prohibited seems to me to be definitive. It's not necessary to explicitly say that mutable objects may be mutated.
The fact that the lifetime of compound literals inside function bodies is automatic can lead to subtle bugs:
/* This is fine */
const char* foo(void) {
return "abcde";
}
/* This is not OK */
const int* oops(void) {
return (const int[]){1, 2, 3, 4, 5};
;

Does the C99 standard permit writing to compound literals (structs)?
By writing to compound literal if you mean modifying elements of a compound literal, then yes, it does if it is not a read only compound literal.
C99-6.5.2.5:
If the type name specifies an array of unknown size, the size is determined by the initializer list as specified in 6.7.8, and the type of the compound literal is that of the completed array type. Otherwise (when the type name specifies an object type), the type of the compound literal is that specified by the type name. In either case, the result is an lvalue.
It means, compound literals are lvalues like arrays, and elements of a compound literal can be modified, just like you can modify an aggregate type. For example
// 1
((int []) {1,2,3})[0] = 100; // OK
// 2
(char[]){"Hello World"}[0] = 'Y'; // OK. This is not a string literal!
// 3
char* str = (char[]){"Hello World"};
*str = 'Y'; // OK. Writing to a compound literal via pointer.
// 4
(const float []){1e0, 1e1, 1e2}[0] = 1e7 // ERROR. Read only compound literal
In your code what you are trying to do is modifying a compound literal element which is pointing to a string literal which is non-modifiable. If that element is initialized with a compound literal then it can be modified.
struct bar *baz = &(struct bar){.a = (char[]){"foo bar"}, .g = 5};
This snippet will work now
Segfaults
(baz->a)[0] = 'X';
printf( "%s", baz->a );
Further standard also gives an example, in the same section mentioned above, and differentiate between a string literal, compound literal and read only compound literal:
13 EXAMPLE 5 The following three expressions have different meanings:
"/tmp/fileXXXXXX"
(char []){"/tmp/fileXXXXXX"}
(const char []){"/tmp/fileXXXXXX"}
The first always has static storage duration and has type array of char, but need not be modifiable; the last two have automatic storage duration when they occur within the body of a function, and the first of these two is modifiable.

Related

C/C++ Access violation writing when changing array value [duplicate]

I am trying to understand the reason behind not being able to modify a string literal in C.
Why is the following illegal in C?
char* p = "abc";
*p = 'd';
From the C89 Rationale, 3.1.4 String literals:
String literals are specified to be unmodifiable. This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and perform certain optimizations. However, string literals do not have the type array of const char, in order to avoid the problems of pointer type checking, particularly with library functions, since assigning a pointer to const char to a plain pointer to char is not valid. Those members of the Committee who insisted that string literals should be modifiable were content to have this practice designated a common extension (see F.5.5).

Result of comparing hardcoded strings with ==

The following C code attempts to compare hardcoded strings using ==:
#include <stdbool.h>
bool test_address_aliasing() {
const char * a = "1";
const char * b = "1";
return a==b;
}
This will compare pointers to a and b, and an optimizing compiler will most likely combine the references to a and b to store them in the same place, thus resulting in a==b being true. However, a compiler is not required to combine references to equivalent strings, so is the actual result implementation defined? (I am most interested in C99 if the answer depends on the version of the C spec.)
It is unspecified whether or not two string constants with the same content point to the same object. Section 6.4.5p7 of the C11 standard regarding string constants states:
It is unspecified whether these arrays are distinct provided
their elements have the appropriate values. If the program
attempts to modify such an array, the behavior is undefined.
The actual pointer comparison is valid in either case (see C11 6.5.9p6):
Two pointers compare equal if and only if both are null pointers,
both are pointers to the same object (including a pointer to an object
and a subobject at its beginning) or function, both are pointers to
one past the last element of the same array object, or one is a
pointer to one past the end of one array object and the other is a
pointer to the start of a different array object that happens to
immediately follow the first array object in the address
space.
From C standard, 6.4.5 "String literals", item 6:
It is unspecified whether these [string literals] arrays are distinct provided their
elements have the appropriate values.
That means, result of this comparison is unspecified.
Since the question specifically sought advice on C99 (not C17), relevant quotes from the 1999 C standard follow;
Section 6.4.5 "String Literals", para 6 says
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.
Section 6.5.2.5 "Compound literals", para 8.
String literals, and compound literals with const-qualified types, need not designate
distinct objects.
The above also refers to footnote 82, which (while informative, not normative) says;
This allows implementations to share storage for string literals and constant compound literals with the same or overlapping representations.
Para 14 of the same section also provides an example;
EXAMPLE 6 Like string literals, const-qualified compound literals can be placed into read-only memory and can even be shared. For example,
(const char []){"abc"} == "abc"
might yield 1 if the literals’ storage is shared.
Section J.1 (informative) lists a bunch of things that are unspecified in the standard, of which the 14th in the list is
Whether two string literals result in distinct arrays (6.4.5).
From all of the above, it is unspecified whether two string literals with equivalent content are distinct. Two string literals of the form "abc" are allowed but not required to be at the same address in memory. This also means that the result of a (pointer) comparison would be unspecified.
if you do so:
char *a = "1";
char *b ="1";
and then:
if(a==b){ DO SOMETHING} HERE you are comparing the address of memory, where the two pointers are stored.
To compare the content of the memory where the variables are stored(and so to compare the value of the 2 variables) you have to do so:
if(*a == *b){DO SOMETHING}
I hope you mean that

Are arrays variables or constants?

I just want to know: Are arrays in C variables or constants?
I am specially confused about char arrays.
According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
1 An lvalue is an expression (with an object type other than void)
that potentially designates an object;64) if an lvalue does not
designate an object when it is evaluated, the behavior is undefined.
When an object is said to have a particular type, the type is
specified by the lvalue used to designate the object. A modifiable
lvalue is an lvalue that does not have array type, does not have an
incomplete type, does not have a constqualified type, and if it is a
structure or union, does not have any member (including, recursively,
any member or element of all contained aggregates or unions) with a
constqualified type.
So arrays are non-modifiable lvalues. that is you may not write for example
char s1[] = "hello";
char s2[] = "hello";
s1 = s2;
The compiler will issue a diagnostic message that the code is invalid.
As for string literals then they have static storage duration and any attempt to modify a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
Compare these two code snippets.
char s[] = "hello";
s[0] = 'H';
and
char *s = "hello";
s[0] = 'H';
In the first code snippet there is declared a character array that is initialized by a string literal. That is the characters of the string literal are used to initialize the elements of the array. And you may to change the created array.
In the second code snippet there is declared a pointer to a strig literal. And in the second statement there is an attempt to change the string literal using the pointer that results in undefined behavior.
As for qualifiers like the const qualifier then (6.7.3 Type qualifiers)
9 If the specification of an array type includes any type
qualifiers, the element type is so qualified, not the array type. If
the specification of a function type includes any type qualifiers, the
behavior is undefined
So this declaration
const char s[] = "hello";
means that each element of the array has the qualifier const in its type specification that is each element has the type const char.
Array Definition:
Like any other variables, uninitialized array elements contain garbage values.
An array is a group of contiguous memory locations that all have the same type.To refer to a particular location or element in the array, we specify the array’s name and the position number of the particular element in the array.
"C How To Program _ Deitel" book.
So as you can see arrays are memory location, thus you can initialize them and make them constants or you can use them as variables.
Array Specifying:
Are like variables definition. You should specify their type and their name and their length(in this case they are different from variables) e.g. int average[10] are sequence of memory that store 10 variable in it.
Character arrays:
In C are null_terminated and always end with '/0' or simply 0. For instance if you want to enter a name with 5 character you must define an array with length 5 + 1('\0'). If you don't you'll encounter an undefined behavior(UB).
You can initialize array in these ways:
char string[] ="computer"
char string[12]="algorthm"
char string[]={'s','t','a','c','k','/0'}

Array as compound literal [duplicate]

This question already has answers here:
Why are compound literals in C modifiable
(2 answers)
Closed 4 years ago.
In C99 we can use compound literals as unnamed array.
But are this literals constants like for example 100, 'c', 123.4f, etc.
I noticed that I can do:
((int []) {1,2,3})[0] = 100;
and, I have no compilation error and is guessable that the first element of that unnamed array is modified with 100.
So it seems as array as compound literal are lvalue and not constant value.
It is an lvalue, we can see this if we look at the draft C99 standard section 6.5.2.5 Compound literals it says (emphasis mine):
If the type name specifies an array of unknown size, the size is
determined by the initializer list as specified in 6.7.8, and the type
of the compound literal is that of the completed array type. Otherwise
(when the type name specifies an object type), the type of the
compound literal is that specified by the type name. In either case,
the result is an lvalue.
If you want a const version, later on in the same section it gives the following example:
EXAMPLE 4 A read-only compound literal can be specified through
constructions like:
(const float []){1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6}
We can find an explanation of the terminology in this Dr Dobb's article The New C: Compound Literals and says:
Compound literals are not true constants in that the value of the
literal might change, as is shown later. This brings us to a bit of
terminology. The C99 and C90 Standards [2, 3] use the word “constant”
for tokens that represent truly unchangeable values that are
impossible to modify in the language. Thus, 10 and 3.14 are an integer
decimal constant and a floating constant of type double, respectively.
The word “literal” is used for the representation of a value that
might not be so constant. For example, early C implementations
permitted the values of quoted strings to be modified. C90 and C99
banned the practice by saying that any program than modified a string
literal had undefined behavior, which is the Standard’s way of saying
it might work, or the program might fail in a mysterious way. [...]
As far I remeber you are right, compound literals are lvalues*, you can also take pointer of such literal (which points to its first element):
int *p = (int []){1, 2, 3};
*p = 5; /* modified first element */
It is also possible to apply const qualifier on such compound literal, so elements are read-only:
const int *p = (const int []){1, 2, 3};
*p = 5; /* wrong, violation of `const` qualifier */
*Note this not means it's automatically modifiable lvalue (so it can used as left operand for assignment operator) since it has array type and refering to C99 draft 6.3.2.1 Lvalues, arrays, and function designators:
A modifiable lvalue is an lvalue that does not have array type, [...]
Referring to the C11 standard draft N1570:
Section 6.5.2.5p4:
In either case, the result is an lvalue.
An "lvalue" is, roughly, an expression that designates an object -- but it's important to note that not all lvalues are modifiable. A simple example:
const int x = 42;
The name x is an lvalue, but it's not a modifiable lvalue. (Expressions of array type cannot be modifiable lvalues, because you can't assign to an array object, but the elements of an array may be modifiable.)
Paragraph 5 of the same section:
The value of the compound literal is that of an unnamed object
initialized by the initializer list. If the compound literal occurs
outside the body of a function, the object has static storage
duration; otherwise, it has automatic storage duration associated with
the enclosing block.
The section describing compound literals doesn't specifically say that whether the unnamed object is modifiable or not. In the absence of such a statement, the object is taken to be modifiable unless the type is const-qualified.
The example in the question:
((int []) {1,2,3})[0] = 100;
is not particularly useful, since there's no way to refer to the unnamed object after the assignment. But a similar construct can be quite useful. A contrived example:
#include <stdio.h>
int main(void) {
int *ptr = (int[]){1, 2, 3};
ptr[0] = 100;
printf("%d %d %d\n", ptr[0], ptr[1], ptr[2]);
}
As mentioned above, the array has automatic storage duration, which means that if it's created inside a function, it will cease to exist when the function returns. Compound literals are not a replacement for malloc.
Compound literals are lvalues and it's elements can be modifiable. You can assign value to it. Even pointer to compound literals are allowed.

Are the literal and constant the same concept in C?

Are the literal and constant the same concept in C?
Is there any difference between them in usage?
Literals and constants are significantly different things in C. It can be said that the term literal in C stands for unnamed object that occupies memory (literals are typically lvalues), while the term constant stands for (possibly named) value that does not necessarily occupy memory (constants are rvalues).
"Classic" C (C89/90) had only one kind of literal: string literal. There were no other kinds of literals in that C. C99 additionally introduced so called compound literals.
Meanwhile, the term constant refers to explicit values, like 1, 2.5f, 0xA and 's'. Additionally, enum members are also recognized as constants in C.
Again, since literals in C are lvalues, you can take and use their addresses
const char *s = "Hello";
char (*p)[6] = &"World";
int (*a)[4] = &(int []) { 1, 2, 3, 4 };
Since constants are rvalues, you can't take their addresses.
Objects declared with const keyword are not considered constants in C terminology. They cannot be used where constant values are required (like case labels, bit-field widths or global,static variable initialization).
P.S. Note that the relevant terminology in C is quite different from that of C++. In C++ the term literal actually covers most of what is known in C as constants. And in C++ const objects can form constant expressions. People are sometimes trying to impose C++ terminology onto C, which often leads to confusion.
(See also Shall I prefer constants over defines?)
The C standard (specifically ISO/IEC 9899, Second edition, 1999-12-01) does not define “literal” by itself, so this is not a specific concept for C. I find three uses of “literal”, described below.
First, a string literal (or “string-literal” in the formal grammar) is a sequence of characters inside quotation marks, optionally prefixed with an “L” (which makes it a wide string literal). This is undoubtedly called a literal because each character in the string stands for itself: A ”b” in the source text results in a “b” in the string. (In contrast the characters “34” in the source text as a number, not a string, result in the value 34 in the program, not in the characters “3” and “4”.) The semantics of these literals are defined in paragraphs 4 and 5 of 6.4.5. Essentially, adjacent literals are concatened ("abc" "def" is made into "abcdef"), a zero byte is appended, and the result is used to initialize an array of static storage duration. So a string literal results in an object.
Second, a compound literal is a more complicated construct used to create values for structures. “Compound literal” is an unfortunate name, because it is not a literal at all. That is, the characters in the source text of the literal do not necessarily stand for exactly themselves. In fact, a compound literal is not even a constant. A compound literal can contain expressions that are evaluated at run-time, including function calls!
Third, in 6.1 paragraph 1, the standard indicates that “literal words and character set members” are indicated by bold type. This use of “literal” is describing the standard itself rather than describing things within the C language; it means that “goto” in the standard means the string “goto” in the C language.
Aside from string literals, I do not think “literal” is a particular concept in C.
”Constant”, however, is a significant concept.
First, there are simple constants, such as “34”, “4.5f”, and “'b'”. The latter is a character constant; although written with a character, it has an integer value. Constants include integer constants (in decimal, octal, and hexadecimal), floating constants (in decimal and hexadecimal), character constants, and enumeration constants. Enumeration constants are names specified in “enum” constructs.
Second, there are constant expressions, defined in 6.6. A constant expression can be evaluated during translation (compile time) rather than run time and may be used any place that a constant may be. 6.6 sets certain rules for constant expressions. As an example, if x is a static array, as declared by static int x[8];, then &x[(int) (6.8 * .5)] is a constant expression: It is the address of element 3 of x. (You would rarely using floating-point to index arrays, but I include it in the example to show it is allowed as part of a constant expression.)
Regarding “const”: The standard does not appear to specifically define a const-qualified object as constant. Rather, it says that attempting to modify an object defined with a const-qualified type through an lvalue (such as a dereferenced pointer) with non-const-qualified type, the behavior is undefined. This implies a C implementation is not required to enforce the constantness of const objects. (Also, note that having a pointer-to-const does not imply the pointed-to object is const, just that the dereferenced pointer is not a modifiable lvalue. There could be a separate pointer to the same object that is not const-qualified. For example, in int i; int *p = &i; const int *q = p;, q is a pointer-to-const-int, but i is not a const object, and p is a pointer to the same int although it is pointer-to-int, without const.)
Not quite. Constant variables (as opposed to constants defined in macros) are actual variables with dedicated storage space, so you can take the address of them. You can't take the address of a literal.
Edit: Sorry everyone, it appears that I was mistaken.

Resources