Memory allocation for global and local variables

前端 未结 3 1130
花落未央
花落未央 2020-12-13 16:29

I have learnt that memory for global variables are allocated at program startup whereas memory for local variables are allocated whenever function call is made.

3条回答
  •  时光取名叫无心
    2020-12-13 16:41

    Cases 2, 3

    Variables that you define inside functions are allocated on the stack. That means that the associated memory is cleaned up (the stack is "popped") when the function exits.

    Case 1

    Variables defined in global scope are allocated in a data segment (or, generally, a memory space requested from the operating system) that exists for the lifetime of the process.

    Additionally

    Memory allocated using malloc is allocated from a heap and remains allocated until explicitly released using free.

    Note that a modern OS may well provide address space requested by a program, but not physically back that address space with RAM until the memory (or a portion of the memory often called a page) is physically accessed.

提交回复
热议问题