Where is const data stored?

For instance:

In the demo.c file,

 #inlcude<stdio.h> int a = 5; int main(){ int b=5; int c=a; printf("%d", b+c); return 0; } 

For int a = 5 compiler converts this to something like a 0x5 storage at a virtual memory address, for example, Ox0000000f in the const area, so for int c = a it translates to something like movl 0x0000000f %eax

Then, for int b = 5 number 5 does not fit into the const region, but is translated directly into the assembly instruction, for example mov $0x5 %ebx .

+5
source share
2 answers

It depends. Your program has several constants:

 int a = 5; 

This is a “static” initialization (which occurs when the program text and data are loaded before starting). The value is stored in memory reserved a , which is located in the "program section of the read-write data section". If something changes a , the value 5 is lost.

 int b=5; 

This is a local variable with a limited scope (only main() ). Storage may be a processor register or a location on the stack. Instructions created for most architectures will contain a value of 5 in the instruction as “immediate data” for the x86 example:

 mov eax, 5 

The ability for instructions to hold arbitrary constants is limited. Small constants are supported by most CPU instructions. Large constants are usually not supported directly. In this case, the compiler will save the constant in memory and load it. For instance,

  .psect rodata k1 dd 3141592653 .psect code mov eax k1 

The ARM family has a powerful design for loading most constants: any 8-bit constant value can be rotated any number of times. See this page 2-25.

The statement contains not one obvious, but a completely different element:

 printf("%d", b+c); 

The string %d in modern semantics of C, is a constant array of three char . Most modern implementations will store it in permanent memory, so attempts to change it will cause SEGFAULT, which is a CPU error at a low level, which usually causes the program to interrupt instantly.

  .psect rodata s1 db '%', 'd', 0 .psect code mov eax s1 push eax 
+1
source

In an OP program, a is "initialized" "global." I expect it to be placed in the initialized part of the data segment. See https://en.wikipedia.org/wiki/File:Program_memory_layout.pdf , http://www.cs.uleth.ca/~holzmann/C/system/memorylayout.gif (from additional information about the executable memory layout program (process) ). The location of a determined by the linker compiler duo.

On the other hand, if automatic (stack) variables, b and c are expected in the stack segment.

Saying that the compiler / linker has the right to perform any optimization if the observed behavior is not violated ( What is the "as is" rule? ). For example, if a never referenced, it can be fully optimized.

+1
source

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


All Articles