How is the memory layout of a C/C++ program?

后端 未结 6 2057
感动是毒
感动是毒 2021-01-31 22:00

I know that there are sections like Stack, Heap, Code and Data. Stack/Heap do they use the same section of memory as they can grow independently? What is this code section? When

6条回答
  •  悲哀的现实
    2021-01-31 22:08

    There's very little that's actually definitive about C++ memory layouts. However, most modern OS's use a somewhat similar system, and the segments are separated based on permissions.

    Code has execute permission. The other segments don't. In a Windows application, you can't just put some native code on the stack and execute. Linux offers the same functionality- it's in the x86 architecture.

    Data is data that's part of the result (.exe, etc) but can't be written to. This section is basically where literals go. Only read permission in this section.

    Those two segments are part of the resulting file. Stack and Heap are runtime allocated, instead of mapped off the hard drive.

    Stack is essentially one, large (1MB or so, many compilers offer a setting for it) heap allocation. The compiler manages it for you.

    Heap memory is memory that the OS returns to you through some process. Normally, heap is a heap (the data structure) of pointers to free memory blocks and their sizes. When you request one, it's given to you. Both read and write permissions here, but no execute.

    There is read-only memory(ROM). However, this is just the Data section. You can't alter it at runtime. When you make a const variable, nothing special happens to it in memory. All that happens is that the compiler will only create certain instructions on it. That's it. x86 has no knowledge or notion of const- it's all in the compiler.

提交回复
热议问题