Windows core programming-memory Stack

Source: Internet
Author: User

The third mechanism for memory operations is to use stacks. A stack can be used to allocate many small data blocks. For example, to manage a chain table and a link tree, the best way is to use a stack. The advantage of a stack is that the issue of allocation granularity and page boundaries can be ignored, focus on the tasks at hand. The disadvantage of the stack is that the memory block allocation and release speed is slower than other mechanisms, and physical memory submission and recovery cannot be directly controlled.
Internally, a stack is a region of the reserved address space. At the beginning, most pages in the reserved area are not submitted to the physical storage. When more memory is allocated from the stack, the stack manager submits more physical memory to the stack. Physical memory is always allocated from the system's page files. When the memory block in the stack is released, the stack manager will reclaim the physical memory.

Thread Stack:

Every time a thread is created, the system reserves a stack space area for the stack of the thread (each thread has its own stack, and submit some physical storage to this reserved area. By default, the system reserves 1 MB of address space and submits two pages of memory. However, these default values can be modified by setting the/s ta c k option of The Link program for m I c r o s o f t when you connect the application:

 

/STACK:reserve[,commit]

When a thread stack is created, the system retains the address space area specified by the/s ta c k switch of a linked program.
Default process stack

When a process is initialized, the system creates a stack in the address space of the process. This stack is called the default stack of a process. By default, the address space of the stack is 1 MB. However, the system can expand the default stack of the process to make it greater than its default value. When creating an application, you can use the/h e a p link to change the default size of the 1 m B area of the stack. Because d l does not have a stack related to it,/h e a p link should not be used when linking d L. The syntax of the/h e a p link switch is as follows:

 

/HEAP:reserve[,commit]

Many wi n d o w s functions require the process to use its default stack. In particular, the APIS provided by widows. Access to the default stack is sequential. In other words, the system must ensure that only one thread can allocate and release memory blocks in the default stack at a time within the specified time. If two threads try to allocate memory blocks in the default stack at the same time, only one thread can allocate memory blocks, and the other thread must wait for the memory blocks of the first thread to be allocated, to allocate its memory block. Once the memory block of the first thread is allocated, the stack function allows the second thread to allocate memory blocks. This sequential access method has a certain impact on the speed. If your application only has one thread and you want to access the stack as quickly as possible, you should create your own independent stack instead of using the default stack of the process.

A single process can have several stacks at the same time. These stacks can be created and withdrawn during the life cycle of a process. However, the default stack is created before the process starts execution and is automatically revoked when the process stops running. You cannot undo the default stack of a process. Each stack is identified by its own stack handle. All stack functions used to allocate and release memory blocks in the stack need this stack handle as its parameter.

You can call the g e t p r o c e s h e a p function to obtain the handle of your process's default stack:

 

HANDLE GetProcessHeap();

Why do we need to create a secondary stack?

Apart from the default stack of the process, you can create some auxiliary stacks in the address space of the process. You may want to create a secondary stack in your application for the following reasons:

• Protection components.

• More effective memory management.

• Local access.

• Reduce thread synchronization overhead.

• Rapid release.

Protection components
By creating multiple independent stacks, data is isolated and operated independently of each other.
More Effective Memory Management

By allocating objects of the same size in the stack, you can manage the stack more effectively. Objects of the same size are placed in a stack for allocation.
Local access

Whenever the system must exchange the r a m page between the r a m page and the system's page files, the system's running performance will be greatly affected. If frequent access to memory is limited to a small range of addresses, then the system is unlikely to need to exchange pages between the r a m and the disk.

Therefore, when designing an application, if some data will be accessed at the same time, it is best to allocate them to the locations close to each other.
Reduce thread synchronization overhead

As described below, the stack runs sequentially according to the default settings, so that if multiple threads attempt to access the stack at the same time, data will not be damaged. However, the stack function must execute additional code to ensure the thread security of the stack. If you want to perform a lot of stack allocation operations, executing these additional code will increase the burden and reduce the running performance of your application. When creating a new stack, you can tell the system that only one thread will access the stack, so the additional code will not be executed. (Multiple stacks are used to reduce synchronization performance consumption)
Quickly release stacks

The last note is that after a dedicated stack is used for some data structures, the entire stack can be released without explicitly releasing each memory block in the stack. For example, when Windows Explorer traverses the directory hierarchy of a hard drive, it must create a tree structure in the memory. If you tell Windows Explorer to refresh its monitor, it just needs to undo the stack containing the tree structure and re-run it (assuming that it uses the dedicated stack to store the directory tree information ). For many applications, this is very convenient and they can run faster.

How to Create a secondary Stack

You can create a secondary stack in the process by letting the thread call the h e a p c r e a t e function:

 

HANDLE HeapCreate(   DWORD fdwOptions,   SIZE_T dwInitialSize,   SIZE_T dwMaximumSize);

When trying to allocate a memory block from the stack, the H e a p a l o C function (which will be described below) must perform the following operations:

1) traverse the allocated and released memory block chain tables.

2) find the address of an idle memory block.

3) Mark idle memory blocks as "allocated" to allocate new memory blocks.

4) Add the new memory block to the memory block chain table.

Allocate memory blocks from the stack

To allocate memory blocks from the stack, you only need to call the h e a p a l o C function:

 

PVOID HeapAlloc(   HANDLE hHeap,   DWORD fdwFlags,   SIZE_T dwBytes);

Change the memory block size

It is often necessary to change the memory block size. Some applications allocate a relatively large memory block at the beginning. Then, when all the data is put into the memory block, the size of the memory block is reduced. Some applications have relatively small memory blocks allocated at the beginning. Later, they need to copy more data to the memory blocks and try to increase the size. To change the memory block size, call the h e a p r e a l o C function:

 

PVOID HeapReAlloc(   HANDLE hHeap,   DWORD fdwFlags,   PVOID pvMem,   SIZE_T dwBytes);

Measure the test taker's knowledge about the memory block size.

After the memory block is allocated, you can call the h e a p s I Z E function to retrieve the actual size of the memory block:

 

SIZE_T HeapSize(   HANDLE hHeap,   DWORD fdwFlags,   LPCVOID pvMem);

Release memory blocks

When you no longer need a memory block, you can call the h e a p f r e function to release it:

 

BOOL HeapFree(   HANDLE hHeap,   DWORD fdwFlags,   PVOID pvMem);

Undo stack

If the application no longer needs the stack it creates, you can call the h e a p D e S t r o y function to undo it:

 

BOOL HeapDestroy(HANDLE hHeap);

Call the h e a p D e S t r o y function to release all memory blocks contained in the stack, you can also return the physical memory occupied by the stack and the reserved address space area to the system. If the function runs successfully, h e a p D e S t r o y returns t r u e. If the stack is not explicitly revoked before the process ends, the system will undo it for you. However, the stack can be withdrawn only when the process stops running. If a thread creates a stack, the stack will not be withdrawn when the thread stops running.

Before the process is completely terminated, the system does not allow the default stack of the process to be revoked. If you pass the handle of the default stack of the process to the H e a p D e S t r o y function, the system ignores the call to this function.

Because the process address space can have multiple stacks, you can use the g e t p r o c e s h e a p s function to obtain the handle of the existing Stack:

 

DWORD GetProcessHeaps(   DWORD dwNumHeaps,   PHANDLE pHeaps);

To call the g e t p r o c e s h e a p s function, you must first allocate an array of H a n d l e and then call the following function:

 

HANDLE hHeaps[25];DWORD dwHeaps = GetProcessHeaps(25, hHeaps);if(dwHeaps > 5) {   //More heaps are in this process than we expected.} else{   //hHeaps[0] through hHeap[dwHeaps - 1]   //identify the existing heaps.}

Note: When this function returns, the default stack handle of your process is also included in the array of stack handles.

The h e a p va l I d a t e function is used to verify the integrity of the stack:

 

BOOL HeapValidate(   HANDLE hHeap,   DWORD fdwFlags,   LPCVOID pvMem);

When calling this function, a stack handle is usually required, A sign with a value of 0 (the only valid one is h e a p _ n o _ s e r I a l I Z E ), and transfer n u L for p v m e m. The function then traverses the memory blocks in the stack to ensure that all memory blocks are intact. To make the function run faster, you can pass a specific memory block address for the p v m e m parameter. In this way, the function can only check the validity of a single memory block.

To merge the idle memory blocks in the address and reclaim the memory pages that do not contain the allocated memory blocks, you can call the following function:

 

UINT HeapCompact(   HANDLE hHeap,   DWORD fdwFlags);

Generally, 0 can be transferred for parameter f d w f l a g s, but h e a P _ n o _ s e r I a l I Z e can also be transferred.

The following two functions are used in combination with h e a p l o c k and h e a p u n l o c k:

 

BOOL HeapLock(HANDLE hHeap);BOOL HeapUnlock(HANDLE hHeap);

These functions are used for thread synchronization. When calling the h e a p l o c k function, the calling thread becomes the owner of a specific stack. If any other thread calls the stack function (set the same stack handle), the system suspends the running of the call thread, in addition, the stack cannot wake up until it is unlocked by the h e a p u n l o c k function.

H e a p a l o C, h e a p s I Z E, H E A P F R E and other functions internally call H E A P L o C K and h e a p u n l o c k functions to ensure that the access to the stack can be sequential. It is uncommon to call h e a p l o c k or h e a p u n l o c k.

The last stack function is h e a p Wa l K:

 

BOOL HeapWalk(   HANDLE hHeap,   PPROCESS_HEAP_ENTRY pHeapEntry);

This function is only used for debugging purposes. It enables you to traverse the stack content. You can call this function multiple times.

Zz
 

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.