A program uses different regions of memory for static objects, automatic objects, and dynamically allocated objects

后端 未结 4 2022
滥情空心
滥情空心 2020-12-09 17:57

I am following the book \"C Primer Plus\" and encounter a problem to understand the regions of memory. In the book, it states:

Typically, a p

4条回答
  •  猫巷女王i
    2020-12-09 18:17

    The C standard states that an object can have one of 4 different storage durations. These are:

    • static
    • automatic
    • allocated
    • thread

    The code above addresses the first 3 of these.

    A static object is is declared either at file scope or at local scope with the static modifier. String literals are also static objects.

    An automatic object, typically referred to as a local variable, it declared within a function or an enclosing scope.

    An allocated object is one whose memory is returned by an allocation function such as malloc.

    In practice, compilers will typically place each of these object types in a different area of memory. Static objects are typically placed in the data section of an executable, automatic (read: local) objects are typically stored on the stack, and allocated objects are typically stored on the heap.

    String literals in particular are static objects, and are typically placed in a special part of the data section marked read-only.

    These regions are typically in different distinct regions of memory, however they are not required to be. So while in practice the addresses of objects in each of these regions will be noticeably different, they aren't required to be.

    So you don't really need to "assure" that different types of variables are in different regions. The compiler takes care of that for you depending on how you define them.

提交回复
热议问题