Heap and stack in memory allocation

Source: Internet
Author: User

Reprinted Please note: http://blog.csdn.net/zgh1988/article/details/7470166

1. What is a stack?

2. A Microsoft pen exam.
3. Are Two stack examples written by myself?
4. How can I dynamically apply for a two-dimensional array?

1. What is a stack? 1. Memory Allocation

The memory occupied by a C/C ++ compiled program is divided into the following parts:
1. STACK: the stack zone is automatically allocated and released by the compiler, and stores function parameter values and local variable values. The operation method is similar to the stack in the data structure.
2. Heap-generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
3. Global (static)-the storage of global variables and static variables is put together, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area (BSS ). -The program is released by the system after it ends.
4. Text Constant Area-constant strings are placed here. The program is released by the System
5. program code area-stores the binary code of the function body.

A simple example

// Main. CPP int A = 0;/* Global initialization zone */char * P1;/* Global uninitialized zone */void main () {int B; /* stack */Char s [] = "ABC";/* stack */char * P2;/* stack */char * P3 = "123456 "; /* 123456 in the constant zone, P3 on the stack */static int C = 0;/* Global (static) the initialization zone * // * allocates 10 and 20 bytes in the heap zone */P1 = (char *) malloc (10); P2 = (char *) malloc (20);/* 123456 is placed in the constant area, and the compiler may optimize it into a place */strcpy (P1, "123456 ");}
2. How to Apply for Stack theoretical knowledge

STACK: automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically opens up space for B in the stack.
Heap: the programmer must apply for it and specify the size. In C, the malloc function is like p1 = (char *) malloc (10 ); use the new operator in C ++, such as P2 = new char [10]. Note that P1 and P2 are in the stack. System Response stack after application: as long as the remaining space of the stack is larger than the requested space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list. Application size limit

STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space available from the stack is small.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large. 2. A Microsoft pen exam

6 Which of following C++ code is correct?  (E)(A) int f()    {        int* a = new int(3);        return a;    }(B) int* f()    {        int a[3] = {1, 2, 3};        return a;    }(C) vector<int> f()    {        vector<int> v(3);        return v;    }(D) void f(int *ret)    {        int a[3] = {1, 2, 3};        ret = a;        return;    }(E) none of above

Based on the above instance, we will analyze the usage of the stack space. (A) It is incorrect because int is returned in the function declaration, and A is actually returned as int *. Now let's think about how to change the declaration in the function to int * F (). In this way, does the returned pointer point to the available space? We know that the dynamic space applied for using new is applied for on the stack, and its application and release are all operated by the programmer. Therefore, when the function returns, it will not be released as the function returns. This is different from stack space. When the function returns, the stack space applied for within the function will be released by the system. To ensure program security, the stack space pointer returned by the function is unavailable. But in fact, we can use pointers on any stack space to access the stack space.
(B) It is incorrect because int A [3] = {1, 2, 3} is a local variable, which is located in the stack space. When the function returns, we return pointer A. if the pointer is returned, we will not use the pointer for security reasons. The following example is used to describe the security.

#include <stdio.h>int* f(){int a[3] = {4, 5, 6};return a;}int main(){int *c = f();printf("%d, %d\n", c[0], c[1]);printf("%d, %d\n", c[0], c[1]);return true;}

The output result of this program is 4, 5 1245056,420 1335. Obviously, after the pointer C is returned, C [0] C [1] is directly output. At this time, the stack space is overwritten, so we can output 4 or 5 correctly. However, after the first output function is executed, it may overwrite the content of the original stack space. When the output is performed, the garbage value is output. Therefore, this is not safe. (C) Yes. The reason is the same as that of B (d). There are two reasons. One is that the stack space applied in the function. Second, RET is a form parameter, so the value does not change when the function returns. For example:

#include <stdio.h>void f(int *ret){int a[3] = {1, 2, 3};ret = a;return;}int main(){int *c = NULL;f(c);printf("%x\n", c);return true;}

The result is 0, that is, the value of C has not changed. 3. Are Two stack examples written by myself? To illustrate the reason for option D above, I wrote a program to explain the situation.

# Include <stdio. h> # include <malloc. h> void swap1 (int A, int B) {int temp; temp = A; A = B; B = temp;} void swap2 (int * a, int * B) {int temp; temp = * A; * A = * B; * B = * A;} void requestheap1 (int * array) {printf ("requestheap1% d \ n", array); array = (int *) malloc (sizeof (INT) * 4 ); printf ("requestheap1% d \ n", array);} void requestheap2 (INT ** array) {printf ("% d \ n", * array); * array = (Int *) malloc (sizeof (INT) * 4); printf ("requestheap2% d \ n", * array);} void deleteheap (int * array) {If (array! = NULL) {free (array); array = NULL;} int main () {int tmp1 = 3, tmp2 = 5; swap1 (tmp1, tmp2 ); printf ("tmp1 = % d, tmp2 = % d \ n", tmp1, tmp2); swap2 (& tmp1, & tmp2); printf ("tmp1 = % d, tmp2 = % d \ n ", tmp1, tmp2); int * array1 = NULL; requestheap1 (array1); printf (" requestheap1 return: % d \ n ", array1 ); deleteheap (array1); int * array2 = NULL; requestheap2 (& (array2); printf ("requestheap2 return: % d \ n", array2); deleteheap (array2 ); return true ;}

The program running result is as follows:
In void swap1 (int A, int B), A and B are form parameters. Although the value of form parameters in the function changes, the value of the real parameter is not changed after the function is executed. That is, when swap1 (tmp1, tmp2) is executed, the values of the real parameters tmp1 and tmp2 are assigned to the form parameters A and B, and the value of the form parameter is changed in the function, but the real parameter value is not affected, therefore, after swap1 (tmp1, tmp2) is executed, the values of tmp1 and tmp2 remain unchanged. In void swap2 (int * a, int * B), A and B are both int * types and form parameters. Similarly, the value of the real parameter is not changed after the function is executed. That is, when swap2 (& tmp1, & tmp2) is executed, the tmp1 and tmp2 pointers are assigned to the form parameters A and B. However, in this function, we use a pointer to change the value pointed to by the pointer. That is, temp = * A; * A = * B; * B = temp; similarly, void request1 (int * array), when requestheap1 (array1) is executed, assign array1 to the form parameter array. After performing various operations on the form parameter array in the function, the value of the form parameter does not change directly. So we found that after the function is executed, array1 is still 0. Void request2 (INT ** array), and then perform requestheap2 (& (array2), assign the address of array2 to the form parameter array, and perform * Array Operations in the function, actually it does not change & (array2), but this function changes the value of * array2. Do you understand? 4. How to dynamically apply for a two-dimensional array
#include <stdio.h>#include <malloc.h>void RequestHeap2(int*** array, int m, int n){*array = (int**) malloc(sizeof(int *) * m);for (int i = 0; i < m; i++){(*array)[i] = (int*)malloc(sizeof(int) * n);}}int** RequestHeap1(int m, int n){int** array;array = (int**) malloc(sizeof(int *) * m);for (int i = 0; i < m; i++){array[i] = (int*)malloc(sizeof(int) * n);}return array;}void DeleteHeap(int** array, int m, int n){for (int i = 0; i < m; i++){free(array[i]);array[i] = NULL;}free(array);array = NULL;}void main(){int** ppArray1 = NULL;int** ppArray2 = NULL;int m, n;scanf("%d, %d", &m, &n);ppArray1 = RequestHeap1(m, n);ppArray1[0][0] = 5;printf("%d, %x\n", ppArray1[0][0], ppArray1);DeleteHeap(ppArray1, m, n);RequestHeap2(&(ppArray2), m, n);ppArray2[0][0] = 5;printf("%d, %x\n", ppArray2[0][0], ppArray2);DeleteHeap(ppArray2, m, n);}

We use two methods: (1) int ** requestheap1 (int m, int N), apply for a dynamic two-dimensional array space inside the function, and return a pointer.
(2) void requestheap2 (INT *** array, int M, int N): Use the int *** array parameter to pass the pointer to the first address of a two-dimensional array, to create a two-dimensional array:
Running successful!




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.