Similarities and differences between Java and C + + memory allocations

Source: Internet
Author: User
Tags garbage collection stack pop wrapper

Original link: http://blog.sina.com.cn/s/blog_9d38f2eb01012tr8.html 1. C + +

Five Large memory partitions
In C + +, memory is divided into 5 areas, which are stacks, heaps, free storage, global/static storage, and constant storage.
Stacks are those that are allocated by the compiler when they are needed, and are stored automatically when they are not needed. The variables inside are usually local variables, function parameters, and so on.
Heap, that is, those allocated by the new memory block, their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer is not released, the operating system will automatically recycle after the program finishes.
Free storage, which is the chunk of memory allocated by malloc, he and the heap are very similar, but it is to use free to end their own lives.
Global/static storage, global variables and static variables are assigned to the same memory, in the previous C language, the global variables are divided into initialized and uninitialized, in C + + without this distinction, they share the same memory area.
Constant store, this is a special storage area, they are stored in a constant, not allowed to modify (of course, you have to use improper means can also be modified, and many methods, in the "Const thinking" article, I gave 6 methods)

Explicitly differentiate between stacks and stack
On the BBS, heap and stack of the distinction between the problem, seems to be an eternal topic, it can be seen that beginners are often confused, so I decided to take his first surgery.
First, let's give an example:
void F () {int* p=new int[5];}
This short sentence contains the heap and stack, see new, we should first think, we allocate a heap of memory, then the pointer p. He allocates a stack of memory, so this means that a pointer to a heap of memory is stored in the stack memory. When the program determines the size of the memory allocated in the heap, then calls operator new to allocate memory, then returns the first address of the memory, put it into the stack, and his assembly code under VC6 is as follows:
00401028 Push 14h
0040102A call operator new (00401060)
0040102F Add esp,4
00401032 mov dword ptr [Ebp-8],eax
00401035 mov eax,dword ptr [ebp-8]
00401038 mov dword ptr [Ebp-4],eax
Here, we do not release the memory for simplicity, so how to release it. Is it delete p? O, wrong, should be delete []p, this is to tell the compiler: I delete an array, VC6 will be based on the appropriate cookie information to release the memory work.
Well, let's go back to our topic: What's the difference between stacks and stacks?
The main difference consists of the following points:
1. Different ways of management;
2, the space size is different;
3, can produce different fragments;
4, the growth direction is different;
5. Different ways of distribution;
6, the distribution efficiency is different;
Management mode: For the stack, is the compiler automatically managed, without our manual control; for the heap, the release of the work by the programmer control, easy to produce memory leak.
Space size: Generally in 32-bit system, heap memory can reach 4G of space, from this point of view heap memory is almost no limit. But for the stack, generally there is a certain amount of space, for example, under the VC6, the default stack space size is 1M (as if it is not clear). Of course, we can modify:
Open the project, and then operate the menu as follows: Project->setting->link, select output in category, and then set the maximum stack value and commit in the reserve.
Note: The reserve minimum value is 4byte;commit is kept in the virtual memory of the page file, it set a large stack to open up a larger value, may increase the cost of memory and startup time.
Fragmentation problem: For the heap, frequent new/delete is bound to cause the memory space discontinuity, resulting in a large number of fragments, so that the program efficiency is reduced. For stacks, this problem does not exist because the stack is an advanced queue, they are so one by one corresponding, so that there will never be a memory block from the middle of the stack pop-up, before he pops up, the last of the stack content on his top has been ejected, detailed reference to the data structure, here we will no longer one by one discussion.
Growth direction: For the heap, the growth direction is upward, that is, toward the memory address of the direction of increase, for the stack, its growth direction is downward, is to the memory address to reduce the direction of growth.
Allocation method: The heap is dynamically allocated and there is no statically allocated heap. There are 2 ways to allocate the stack: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is allocated by the Alloca function, but the dynamic allocation and heap of the stack are different, and his dynamic allocation is released by the compiler without our manual implementation.
Allocation efficiency: The stack is a machine system provides the data structure, the computer will be at the bottom of the stack to provide support: the allocation of special registers to store the stack address, pressure stack out of the stack have specific instructions to execute, which determines the stack of high efficiency. The heap is provided by the C + + function library, and its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will search the heap memory for the available space of sufficient size in a certain algorithm (the specific algorithm can refer to the data structure/operating system), if there is not enough space (possibly due to too much memory fragmentation), It is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to get enough memory and then return. Obviously, the heap is much less efficient than the stack.
From here we can see that heap and stack, because of the use of a large number of new/delete, easy to create a lot of memory fragmentation, because there is no special system support, inefficient, because of the possible user-state and nuclear mentality of switching, memory applications, the cost becomes more expensive. So the stack in the program is the most widely used, even if the function of the call also use stack to complete, function calls in the process of parameters, return address, EBP and local variables are used to store the stack. So, we recommend that you try to use stacks instead of heaps.
Although the stacks have so many benefits, they are not as flexible as the heap, and sometimes allocate a lot of memory space, or use a heap better.
Both the heap and the stack are supposed to prevent the occurrence of cross-border phenomena (unless you deliberately make them out of bounds), because the result of crossing the line is either a program crash or a heap or stack structure that destroys the program, resulting in unexpected results, even when your program is running without the above problems, you should be careful Maybe it will collapse when debug is very difficult:
Yes, there is another thing, if someone put the stack together said, it means that the stack, is not a heap, hehe, clear.2. Java

In Java, there are six different places to store data:
1. Register (Register). This is the fastest store because it is located in a different storage area--within the processor. But the number of registers is extremely limited, so the registers are allocated by the compiler according to the requirements. You can't control it directly, and you can't feel any sign of the register in the program.
2. Stacks (Stack). is located in Universal RAM, but it can be supported from the processor by its stack pointer. If the stack pointer moves downward, the new memory is allocated, and the memory is freed if you move up. This is a fast and efficient method of allocating storage, second only to registers. When you create a program, the Java compiler must know the exact size and lifecycle of all the data stored in the stack, because it must generate the appropriate code to move the stack pointer up and down. This constraint limits the flexibility of the program, so although some Java data is stored on the stack-especially object references-Java objects do not store them.
3. Heap (heap). A general-purpose memory pool (also in RAM) for storing so Java objects. The advantage of a heap that differs from the stack is that the compiler does not need to know how many storage areas to allocate from the heap or how long the stored data will survive in the heap. Therefore, allocating storage in the heap has great flexibility. When you need to create an object, you just need to write a simple line of code that, when executed, will automatically store allocations in the heap. Of course, for this flexibility, you have to pay the appropriate code. Storing allocations with a heap requires more time than storing storage on a stack.
4. Static storage (storage). The "static" here means "in a fixed position." Data stored in a static store that always exists when the program is running. You can use the keyword static to identify that a particular element of an object is static, but the Java object itself is never stored in a static storage space.
5. Constant Storage (constant storage). Constant values are usually stored directly inside the program code, and it is safe to do so because they will never be changed. Sometimes, in an embedded system, the constants themselves are separated from other parts, so in this case, you can choose to place them in ROM
6. Non-RAM storage. If the data is completely alive outside of the program, it can be free of any program control and can exist when the program is not running.
in terms of speed, there are the following relationships:
Registers < stacks < Heaps < other

"Thinking in Java" from the above paragraph 3. Stacks and Heaps

Here, the main point is to say the relationship between heap and stack:

  Heap: Heap is heap, is called dynamic memory, where the memory can be recycled when it is not needed to allocate to new memory requests, the data in its memory is unordered, that is, the first allocation and subsequent allocation of memory and there is no inevitable position relationship, release can also be no order. Generally by the user free distribution, malloc allocation is the heap, need to manually release.

  stack: just stack. In fact, there is only one exit queue, that is, LIFO (first in the last out     ), and the allocated memory is bound to be released. Generally by the system automatically allocated, stored functions of the parameter values, local variables, etc., automatic removal.

Also, the heap is global, the stack is the entry of each function is a small block, the function returned when the release, static and global variables, new variables are placed in the heap, local variables on the stack, so the function returned, local variables are all gone.

In fact, in practical applications, the stack is used to store the invocation of the method. The storage that is used for the object.

   The basic types in Java actually require special treatment. Because, in Java, objects created through new are stored in the heap, creating a small, simple variable with new, such as the base type, is often not very effective. Therefore, in Java, for these types, the same methods as C and C + + are used. That is, instead of creating it with new, you create an "automatic" variable that is not a "reference". This variable has its "value" and is placed on the stack, so it is more efficient

Java divides memory into two types: one is stack memory and the other is heap memory.
Some of the basic types of variables and reference variables defined in the function are allocated in the stack memory of the function.
When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.
Heap memory is used to store objects and arrays created by new.
The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.
After generating an array or object in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable for the array or object.
A reference variable is equivalent to a name that is an array or an object, and you can later use the reference variable in the stack to access the array or object in the heap.
In particular, say:
Stacks and heaps are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.
Java's heap is a run-time data area in which the object allocates space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. The heap is responsible for garbage collection, the advantage of the heap is the dynamic allocation of memory size, the lifetime does not have to tell the compiler in advance, because it is dynamically allocating memory at runtime, the Java garbage collector will automatically take away these no longer used data. The disadvantage is that the access rate is slow due to the dynamic allocation of memory at run time.
The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. There are some basic types of variables in the stack (, int, short, long, byte, float, double, Boolean, char), and object handles.
Stack has a very important particularity, is the existence of the stack of data can be shared. Let's say we both define:
int a = 3;
int b = 3;
The compiler deals with int a = 3 First, it creates a reference to a in the stack, finds out if there is a 3 value in the stack, and if not, it stores 3 in, then points a to 3. then process int b = 3, after you create the reference variable for B, because you already have 3 in the stack, point B directly to 3. In this way, there is a case where A and B both point to 3. At this point, if you make a=4 again, the compiler will search for a 4 value in the stack, and if not, put 4 in and point A to 4, and if so, direct a to this address. Therefore the change of a value does not affect the value of B. Note that this sharing of data is different from the two-object reference to an object, because the modification of a does not affect B, it is done by the compiler, and it helps save space. While an object reference variable modifies the internal state of the object, it affects another object reference variable.
A string is a special wrapper class data. Can be used:
String str = new String ("abc");
String str = "ABC";
In two forms, the first is to create a new object with new (), which is stored in the heap. Each time a call is made, a new object is created.
And the second is to create an object reference variable str in the stack on a string class, then find out if there is any "ABC" in the stack, and if not, store "ABC" in the Stack and make str point to "ABC", and If "ABC" is already there, direct STR to "ABC".
When comparing the values in a class with the Equals () method, use = = when testing whether references to two wrapper classes are pointing to the same object, use the following example to illustrate the above theory.
String str1 = "abc";
String str2 = "abc";
System.out.println (STR1==STR2); True
You can see that str1 and str2 are pointing to the same object.

String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
The way to new is to generate different objects. Generate one each time.
So the second way to create multiple "ABC" strings is that there is only one object in memory. This formulation is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual situation of the data in the stack. For code with string str = new String ("abc"), the new object is created in the heap, regardless of whether its string value is equal or not, and it is necessary to create a new object, which increases the burden on the program.
On the other hand, note that when we use a format-definition class such as String str = "ABC", we always assume that the object str of the string class was created. Worry about traps. The object may not have been created. Instead, you might just point to an object that you have previously created. Only the new () method can be used to guarantee that one object is created each time. Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when string variables need to change their values frequently.

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.