C language stack and heap (stack && Heap) pros and cons and their use difference _c language

Source: Internet
Author: User

First, the preface

Until now, we've learned how to declare constant types, such as int,double, and so on, as well as complex examples of arrays and structs. We declare that they have grammar in various languages, such as Matlab,python and so on. In the C language, put these variables in the stack memory.

Ii. basis

1, Stack

What is a stack, it is a special area of your computer's memory, which is used to store temporary variables created by each function (including the Mian () method). Stack is filo, is the advanced principle of the structure, it is closely managed by the CPU and fully utilized. Each function declares a new variable, and it is "pushed" onto the stack. Then every time a function exits, all the variables defined in the function are released (in other words, delete). Once the variables in the stack are released, the area becomes available and is provided to the variables in the other stack.

The advantage of using a stack to store variables is that you manage the memory. You don't have to create the memory manually, and you don't have to manually release the memory when you don't need it. In addition, CPU organization stack memory is very efficient. Reading and writing stack variables is fast.

The key to understanding the stack is to understand the concept, when a function exits, all its variables will be popped from the stack, will disappear forever. Therefore, the variables in the stack are local in nature. This is related to what we originally understood as variable scopes or local or global variables. In C, a public bug is an attempt to access a variable in the stack from outside a function in your program (after the function has exited).

Another feature of the stack is that we should remember that there are limits to the size of the variables in the storage stack. and the creation of variables on the heap is not considered.

Summary stack:
A, the growth and expansion of the stack is the function of pressure or the introduction of local variables.
b, we do not have to manage our own memory, the creation and release of variables are automatic.
c, the variables in the stack only exist when the function is created and run.

2, Heap

The heap is also an area of our computer's memory, but he is not automatically managed. and is not closely managed by the CPU. It is a more free area of memory (very large). To create memory on the heap, we must 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 failure, your program will have a memory leak. In other words, heap memory is always there, and other processes are unusable. We'll be debugging the section to see that there's a thing called Valgrind that can help you find memory leaks.

Unlike stacks, the heap has no limit on the size of variables (except for the physical limitations of your computer). Heap memory reads out and writes slowly because it must use a pointer graph to access heap memory. We'll explain the pointers below.

3, stack and heap of advantages and disadvantages

Stack:
A, quick access.
b, there is no need to explicitly create a taxonomy variable because it is automatically managed.
C, space is managed efficiently by the CPU, memory will not become fragmented.
D, only local variables
E, limited by stack size (depending on the operating system)
F, variable cannot be resized.
Heap:
A, variables can be accessed globally
b, no memory size limit
C, (relative) access is relatively slow
D, there is no efficient use of space, as block memory is created and destroyed, memory may become fragmented.
E, you have to manage the memory (variable creation and destruction you have to be responsible for)
F, variable size can be adjusted with realloc ()
For example:
Here is a short program that creates variables on the stack. Similar to other programs we see

 #include <stdio.h>
 double multiplybytwo (double input) {
 double twice = input * 2.0;
 return twice;
 }
 int main (int argc, const char * argv[]) {
 int age = =;
 Double salary = 12345.67;
 Double Mylist[3] = {1.2,2.3,3.4};
 printf ("Double Your salary is%.3f\n", Multiplybytwo (Salary));
 return 0;
 }


  
The results of the operation are as follows: Double your salary is 24691.340

In lines 7th, 8 and 9, we declared three variables: an int variable, a double variable, and an array containing three double arrays. 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 then stack. Similarly, in the Multiplybytwo function, the second double variable is pushed into the stack when the Multiplybytwo () function is created. Once the function exits, the second variable will stack up and disappear 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 a variable with the static keyword. A variable is declared with a static key, so it becomes something similar to a global variable. But it is only visible in the function that creates it. This is a strange thing unless you need it in a very special case.

The following is another version of the creation variable on the heap rather than 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 release it with free (). It's not a big deal, but it's bulky. 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 real values. We'll discuss the pointers below. The pointer on the C stack is a special data type that stores the address of the memory instead of storing the actual values. So in

*twice = *input *2.0;


  
This line, the twice variable is not a double, but a pointer to double, which is the address in the double that is stored in memory.

4. When to use the heap

When should we use heaps and stacks? If we need to allocate a 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're dealing with a very small variable, and as long as it survives when the function is used, then you should use the stack, which is convenient and fast. If you need a variable similar to an array or structure, and can dynamically resize (for example, an array can add data or delete data as needed), you can use malloc (), realloc () to allocate heap memory to them, and use free () to manage the memory manually. When we're done talking about pointers, we'll discuss dynamic allocation of data structure bodies.

Through the above stack and heap of the introduction, I hope to understand and distinguish between stack and heap help.

Related Article

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.