Will the string initializer lose some memory?

To initialize a char array, I usually write:

char string[] = "some text";

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

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

I told him that it was crazy to give up readability and brevity, but he claimed that initializing a char array with a string would actually create two lines, one of them on the stack and the other in read-only memory. When working with embedded devices, this can lead to unacceptable memory waste.

Of course, line initializers seem clearer, so I will use them in my programs. But the question is, will the line initializer create two identical lines? Or are string initializers just syntactic sugars?

+4
source share
6 answers
char string[] = "some text";

100% equivalent

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

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

There is no way to avoid read-only storage, as all data must be placed somewhere. You cannot select string literals in the air. All you can do is move it from one read-only memory segment to another, which will ultimately give you the same program size.

The first style is preferable because it is more readable. It is truly a form of syntactic sugar.

, , " ", "some text" . -, , .

+6

. .

: , sizeof , , . memcmp .

, : .

( ), . , , .

+6

C " ", :

§6.7.9/14 UTF-8, . ( , ) .

. , . ++, , C . . , , , , .

+3

. .

http://gcc.godbolt.org/ :

  • , movb ( ) .

  • , movabsq / movq, .

  • , .rodata.

. , gcc movabsq char string[] = "string literal";, ( ).

, , .

, - , , . , , , . ( , , , .)

, , , . , .

+3
  • string[] 10 , .

  • string[] 10 , .

, . - ( ).

, , , . . , , , , :

const char* string = "some text" ;

string :

#define string "some text"

" " , string. ( / ). string , , , . , const char* string, sizeof(string) - , string[] ( nul-)

+1

? - ?

:

1- :

char string[] = "some text";  // <-- string initialization

. \0 , , , printf, , ( %s).


:

char string[] = {'s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't'};  // <--  array initialization

, string. (, int, long ..). \0 . , WRONG printf char %s.


, , . , , - .

0

Source: https://habr.com/ru/post/1629107/


All Articles