Search code examples
assemblycpuheap-memorystack-memory

Are the Heap, the Stack and the Data segment on the same assembly program?


As far as i know, an assembly program is devided to two- 1)the code 2)the data. Now, when we code, say on c\c++, the code is loaded to the memory and then the CPU starts execute the code, one instruction by one, as an assembly program. My questions are: 1. where is the c code stored? I mean, when I'm running a program in Visual Studio, is the code loaded to one of them- Heap,Stack..? 2. So the memory is virtually divided to Stack,Heap and Date segment, but when the CPU executes the program, as an assembly program, are they all 1 assembly program with the same data area or they are formed in to,lets say 2 or 3 assebmly program thats jumps from one to another?

** Let me add this question, maybe it will clarify my intention: When I'm launching a C program, the code (machine instructions) is loaded to the memory. So, this is one assembly program. But how does the memory division take place? I mean, how des the different memory sections such as Stack, Data segment, etc. modify the assembly program?


Solution

  • The segments or sections are contiguous divisions in object and executable files, much like chapters in a book. The stack and bss sections do not exist in the file but are created at runtime.

    The point of the sections is mostly to divide the program into areas that the operating system can protect in different ways. In order to arrange for that, the sections must start on page boundaries and be contiguous in memory.

    The basic ("important") sections are...

    text or code - the OS will write-protect this section, and since it's immutable, it can also share it between multiple processes or threads running the same executable

    data - the OS will map this r/w and won't directly1 share it

    bss - this section consists of zero-initialized data.

    stack - typically separated from the program, it generally grows downward from higher addresses

    The last two sections aren't in the executable file because they don't need any intiialization.

    If you are asking about how they are implemented, well, the assembler and linker create a table-of-contents and write out the sections in binary like chapters in a book. The OS then reads them separately and puts them in different sections of the address space.

    The specifics and the terminology are different between Unix-like systems and Windows, but the principles are the same.


    1. Yeah yeah, copy-on-write allows for sharing data too, kind of.