C ++ memory allocation in an interesting little problem (the original blog garden already published article can not be re-used markdown to write that way)

The following code test environment: vs2019

statement of problem

The implementation of such a code, and see what happens:

int arr[5] = { 0 };
int main()
{
    arr[5] = 1;
}

There is no doubt, I will complain, because the access violation.


Look at another piece of code:

int arr[5] = { 0 };
int main()
{
    arr[5] = 1;
}

Almost no difference compared with the above code, only the arr definition and initialization function moved outside, but the execution of the program without error.

There are so many similar piece of code:

int main()
{
    static int arr[5] = { 0 };
    arr[5] = 1;
}

The same can be executed successfully, then this is why?


Explore issues

The following excerpt

In C++the memory is divided into five areas, namely the heap , stack , free store , global / static memory and a constant memory area .
Heap : heap is the term operating system, the operating system is maintained by a special memory, dynamic memory allocation for the program Clanguage mallocfrom the memory allocated on the heap using freethe release of the corresponding memory allocated.
Stack : during a function, the memory cell can function in a local variable stack created on the memory cells automatically released at the end of the function execution. Stack memory allocation operation in the processor instruction set, high efficiency, but the limited amount of memory allocated.
Free store : free storage area is C++based on newan abstract concept of the operator, who by newmemory-operator application, the memory is the free store .
Global / static storage area : this memory is in the program compile time already-allocated, are present during the entire program run. Such as global variables , static variables .
Constant storage area: This is a special storage area inside the store they are 常量(const)not allowed to modify.

The above issues relate to two areas: the stack and global / static storage area .


Personal speculation

Based on these findings, I have a little premature speculation:

  • Stack space is a good distribution of the predetermined system, if I is defined int arr[5], then the system will give (32-bit system) I 5 * 4 bytes of space, the system does not allow me to access data on exceeding the address space.
  • Global / static storage area is different, when I defined int arr[5], the system returns to me arrthe first address , I not only had access to 20 bytes of content according to the first address, you can also access content outside of twenty bytes.

Guess you like

Origin www.cnblogs.com/XiaoXiaoShuai-/p/12452795.html