Stacks and heaps (stack && heap)

Source: Internet
Author: User

First, preface       Until now, we have known how we declare constant types, such as int,double, and so on, as well as complex examples such as arrays and structs. We declare that they are in various languages of the grammar, such as Matlab,python and so on. In the C language, these variables are placed in the stack memory. Ii. Basic      1, stacks           What is a stack, which is a special area of your computer's memory, It is used to store temporary variables created by each function (including the Mian () method). Stack is filo. Is the advanced after-out principle of the structure, it is closely managed by the CPU and fully utilized. Each time the function declares a new variable, it is "pushed" into the stack. Then each time a function exits, all variables defined in the function are freed (in other words, deleted). Once the variables in the stack are released, the area becomes available and provided to the variables in the other stacks.       The advantage of storing variables with stacks is that the memory is managed by you. You don't have to create the memory manually, and you don't have to manually free the memory when you don't need it. In addition, CPU stack memory is very efficient. Read-out and write-stack variables are fast.       Understanding stacks is the key to understanding the concept, when a function exits, all its variables will be popped out of the stack, and will disappear forever. So the variables in the stack are essentially local. This is related to what we originally understood as variable scopes or local or global variables. In C, a common bug is to try to access a function in the stack from a function outside of your program (after the function has exited).       about another feature of the stack we should keep in mind that there is a limit to the size of the variables stored in the stack. Create variables on the heap without consideration.       Summary stack:      A, stack growth and scaling are functions that press in or roll out local variables.       B, we don't have to manage the memory ourselves, variable creation and release are automatic.       C, the variables in the stack only exist when the function is created at run time.      2, heap           Heap is also an area of our computer's memory, but he is not automatically managed. And it's notis tightly managed by the CPU. It is a more liberal area of memory (very large). To create memory on the heap, we have to use malloc () or calloc (), which are compiled in C language. Once you allocate memory on the heap, you must use free () to destroy it when you are not in need. If you do not destroy or destroy the failure, your program will have a memory leak. In other words, the heap memory is always there and other processes are unusable. We'll re-debug the section to see that there is something called Valgrind that can help you discover memory leaks.       Unlike stacks, heaps have no limit on the size of variables (other than the physical limitations of your computer). Heap memory reads and writes are slow because it must use a pointer graph to access heap memory. We will explain the pointers below.     3, stack and heap advantages and disadvantages       Stacks:          A, quick access.           B, there is no need to explicitly create categorical variables because it is automatically managed.           C, space is managed efficiently by the CPU, and memory does not become fragmented.           D, only local variables           E, limited by stack size (depending on operating system)           F, variable cannot be resized.         Heap:          A, variable can be accessed globally           B, no memory size limit and nbsp         C, (relative) access is slow           D, without efficient use of space, memory may become fragmented as block memory is created and destroyed.           E, you must manage memory (variable creation and destruction you have to be responsible for)           F, variable size can be adjusted with realloc () For example: &nbsp             The following is a short program that creates variables on the stack. Similar to the other programs we see
     1, #include <stdio.h>2, double multiplybytwo (double input) {3,    double twice = input * 2.0;4,    return twice;5, }6, int main (int argc, const char * argv[]) {7,    int age = 30;8,    double salary = 12345.67;9,    double mylist[3] = {1.2,2.3,3.4};10,   printf ("Double Your salary is%.3f\n", Multiplybytwo (Salary)); 11,    return 0;12,}

  

The results of the operation are as follows: Double Your salary is 24691.340In lines 7th, 8 and 9, we declare three variables: an int variable, a double variable, and an array containing three double. These three variables are created in the main () function and are pressed into the stack. When the main () function exits (the program exits), the variables are stacked. Similarly, in the Multiplybytwo function, the second double variable is also pressed into the stack when the Multiplybytwo () function is created.     Once the function exits, the second variable goes out of the stack and disappears forever. Note: There is a way to tell C to keep a stack variable. Even if its creation function exits. That's when you declare variables with the static keyword. A variable is declared with the static key, so it becomes something similar to a global variable. But it is only visible in the function that created it.     This is a strange thing, unless you need it in a very special case. Here is another version of the Create variable on the heap instead of on the stack:
#include <stdio.h> #include <stdlib.h> double *multiplybytwo (double *input) {    double *twice = malloc ( sizeof (double));    *twice = *input *2.0;    return twice;} int main (int argc, const char * argv[]) {    int *age = malloc (sizeof (int));    *age = +;    Double *salary = malloc (sizeof (double));    *salary = 12345.67;    Double *mylist = malloc (3 * sizeof (double));    MYLIST[0] = 1.2;    MYLIST[1] = 3.4;    MYLIST[2] = 4.5;    Double *twicesalary = multiplybytwo (salary);       printf ("Double Your salary is%.3f\n", *twicesalary);       Free (age);    Free (salary);    Free (myList);    Free (twicesalary);       return 0;}

  

As you can see, we use malloc () to allocate heap memory and free () to release it. It's not a big deal, but it's cumbersome. There is one more thing to note: This will be a lot of * numbers. These are pointers. The malloc () (Calloc () and free ()) functions handle pointers rather than true values. We will discuss the pointers below. The pointer in the C stack is a special data type that is used to store the memory's address instead of storing the actual values. So in
*twice = *input *2.0;

  

In this line, the twice variable is not a double, but a pointer to a double, which is a double that is stored in the memory again. 4. When to use heaps when should we use heaps and stacks? If we need to allocate a large chunk of memory (such as a large array or a large structure), and we need to keep this variable for a long time (such as global variables). We should allocate heap memory. If you deal with very small variables, and as long as the function is used to survive, then you should use the stack, it is more convenient and fast. If you need a variable similar to an array or struct, and you can dynamically change the size (for example, if an array can add data or delete data as needed), then you can use malloc (), realloc () to allocate heap memory to them and manually manage the memory with free (). When we have discussed the pointers, we will discuss the dynamic allocation of data structure bodies.

Stacks and heaps (stack && heap)

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.