user737163
user737163

Reputation: 471

String literals in sizeof

From my knowledge, string literals are stored in system-protected areas when used in executable code and not initialization. Does this also hold when using string literals in the sizeof function for example:

sizeof("example")

Is this string (char array) even created in memory and if not, where is it created and how does it get the correct result of 8 including the nul character?

Upvotes: 3

Views: 1217

Answers (3)

John Bode
John Bode

Reputation: 123596

Being the operand of sizeof has no effect on where string literals are stored:

6.5.3.4 The sizeof and _Alignof operators
...
2     The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
C 2011 Online Draft

Emphasis added.

IOW, sizeof doesn't care where something is stored, because it's not looking at storage; it's looking at the type of its operand. You can apply sizeof to things that have no storage like arithmetic expressions and numeric literals:

sizeof 100      == sizeof (int)
sizeof (2 * 3)  == sizeof (int)
sizeof (x + y)  == sizeof (whatever the common type of x and y is)

A string literal like "foo" has the type "4-element array of char" (3 characters plus the terminator), so sizeof "foo" evaluates to 4.

Upvotes: 3

Lundin
Lundin

Reputation: 215350

Except for the special case where sizeof is applied to a variable-length array, it is always evaluated at compile-time. The C standard doesn't force compilers to not allocate the string literal in your example, but in practice every compiler I know of will not do so. Instead they will replace the whole expression with the number 8 in the machine code.

Furthermore, note that the operand of sizeof isn't evaluated for side effects either. So code like sizeof("example" + i++); will not increment i. That's where tricks like type* ptr = malloc(sizeof *ptr); come from: the sizeof expression is evaluated at compile-time, without ever de-referencing the pointer.

Upvotes: 0

4386427
4386427

Reputation: 44368

The C standard says nothing about this. It's all up to the compiler.

Most likely the string will not be part of the program but we can't know.

Nitpick: Since the result of sizeof("example") isn't used even that won't go anywhere.

Upvotes: 1

Related Questions