Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a string initializer somewhat waste memory?

To initialize a char array, usually I write:

char string[] = "some text";

But today, one of my classmates said that one should use:

char string[] = {'s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', '\0'};

I told him it is crazy to abandon readability and brevity, but he argued that initializing a char array with a string will actually create two strings, one asides in the stack and another in the read-only memory. When working with embedded devices, this can result in unacceptable waste in memory.

Of course, string initializers seems clearer, so I'll use them in my programs. But the question is, will a string initializer create two same string? Or string initializers are just syntax sugars?

like image 439
nalzok Avatar asked Nov 30 '22 23:11

nalzok


2 Answers

char string[] = "some text";

is 100% equivalent to

char string[] = {'s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', '\0'};

Your friend is confused: if string is a local variable, then in both cases you create two strings. Your variable string which resides on the stack and a read-only string literal which resides in read-only memory (.rodata).

There is no way to avoid the read-only storage, since all data must be allocated somewhere. You cannot allocate string literals in thin air. All you can do is to move it from one read-only memory segment to another, which will give you the very same program size in the end anyway.

The former style is preferred in general, as it is more readable. It is indeed a form of syntactic sugar.

But it is also preferred because it might ease some compiler optimization known as "string pooling", which allows the compiler to store the string literal "some text" in more memory-effective ways. If you initialize the string character-by-character, the compile may or may not realize that it is a read-only string constant.

like image 95
Lundin Avatar answered Dec 04 '22 22:12

Lundin


After your edit, there is no difference between the two definitions. Both will produce an array of ten characters and initialized to the same contents.

This is actually easy to verify: First check what sizeof gives you for the two arrays, then you can use e.g. memcmp to compare both the arrays.

The second initialization is almost equal to the first, with once crucial difference: The second array is not terminated as a string.

The first creates an array of ten characters (including the terminator) and the second creates an array of nine characters. If you don't use the array as a string, then yes you will save once element with the second initialization.

like image 35
Some programmer dude Avatar answered Dec 04 '22 21:12

Some programmer dude