Memory allocation in C language that's the thing.

Source: Internet
Author: User

C Program's memory structure

The complexity of C language, first of all its memory model work is not. Unlike some high-level languages, they only need to be created with new when using objects. After all, you don't have to worry about it. For the C language, all memory-related things need to be familiar with, otherwise, a long time, will always step on the Thunder. Is typical of a C program's memory structure, of course, there is an important premise, such a layout is in virtual memory :

About the virtual memory kernel maintains a page table that represents a mapping between virtual memory for physical memory addresses or disks (swap areas, swap area). Not all virtual addresses need to be mapped on physical memory, otherwise no matter how much memory is on the computer, a few more processes, memory consumption is gone. When you need to use memory to go to the operating system to request, if the request is legitimate, then the kernel for the page table to add table entries, establish a virtual address to the physical address of the mapping between. Similarly, when a release is needed, the mapping is released and the resource is returned.

The advantages of virtual memory "the Linux Programming Interface" gives a more complete answer:

Processes is isolated from one another and from the kernel, so that one process can ' t read or modify the memory of anothe R process or the kernel. This was accomplished by has the Page-table entries for each process point to distinct sets of physical pages in RAM (or In the swap area).

Where appropriate, or more processes can share memory. The Kernel makes this possible by have page-table entries in different processes refer to the same pages of RA M. Memory sharing occurs in, common circumstances: 
–multiple processes executing the same program can share a Single (readonly)  copy of the program code. This type of sharing are performed mplicitly when multiple programs execute the same program file (or load the SAME&NB Sp;shared library).
–processes can use the Shmget () and mmap () system calls to explicitly request sharing of memory regions with OTH ER processes. This was done or the Purpose of interprocess communication.

The implementation of memory protection schemes is facilitated; That's, pagetable entries can be marked to indicate the contents of the corresponding page was readable, writable, E Xecutable, or some combination of these protections. Where multiple processes share pages of RAM, it's possible to specify so each process have different protections on the Memory For example, one process might had read-only access to a page, while another had read-write access.


Programmers, and tools such as the compiler and linker, don ' t need to being concerned with the physical layout of the program In RAM.

Because only a part of a program needs to reside in memory, the program loads and runs faster. Furthermore, the memory footprint (i.e., virtual size) of a process can exceed the capacity of RAM.

One final advantage of virtual memory management is this since each process uses less RAM, more processes can simultaneous LY is held in RAM. This typically leads to better CPU utilization, since it increases the likelihood, at any moment in time, there are at least one process that the CPU can execute.

The main purpose of this paper is to discuss some details of memory allocation in the heap area.

Using System calls

Usually we call the current boundary of the heap "program break". allocating memory in the heap area is the process of moving program break to a high address. There are two system calls in the UNIX system that are most closely related to this program break:

int brk (void *addr);

void *sbrk (intptr_t increment);

SBRK () is the increase and release of memory by the length of the increment to move the program break. Because virtual memory is allocated by page, the value of increment is not the result of the actual allocation. As long as the size of the page is not an integer multiple, it will be more than a page, not rounded, will always only give more, unless there is insufficient memory. SBRK (0) shows the current program break. A Sigsev signal occurs when an attempt is made to access memory outside of program break, and a segment error occurred. The BRK () function and the SBRK () usage are similar.

 1  int   main ()  2  3  int  * p = sbrk (100  ); 4  * (P+1023 ) =4  ;  5  printf ( " **\n   "  6  * (P+1024 ) =4  ;  7 } 

Such a piece of code, to the kernel request 100 bytes of memory, actually mapped is a memory page, row 4 access memory page of the last 4 bytes and overwrite, line 6 access mapping outside the memory is obviously illegal, the program run the result is as follows:

$a. Out

**
Segmentation fault

when memory is freed with BRK ()/sbrk (), the mapping relationship is also not immediately released. It is possible to return the requested physical memory to the kernel when program break drops more than one page. Of course, all the operations on this memory after release are undefined, as with playing with fire. At the same time, it is important to note that program break's position cannot be moved outside the heap area, such as BSS, data area, and so on, which is basically the act of death.

Using C standard library functions

malloc ()/free () is definitely one of the most widely used functions in the C language. The interface is simpler than BRK ()/sbrk () and allows free memory to be freed. (BRK ()/sbrk () is not free to release because the program break moves down the release of memory, the top of the "innocent" element is also released. For example, this is the case (where the memory map is removed):

The free () release does not have such a "pit" because free memory does not necessarily move program break. If you want free () to release the memory above (high memory address) still has no freed memory, then the program break will not move, so it does not de-map the relationship, that is, the memory is not returned to the kernel. Instead, the free memory is left over for maintenance, and when the next malloc application is made, return this memory (if sufficient) to malloc. So how does free know the size of the freed memory? This is because the memory returned by malloc has a relatively special structure:

The size of this memory is recorded in front of this block of memory. When the memory is reclaimed, the length and address of the piece are recorded. When you re-malloc, you compare the free memory list with the required memory and give the program "two use" (or n times). Of course, the use of memory without the free memory list depends on the specific situation:

1. If the spare memory is larger than the malloc application, then a portion of the cut is returned to malloc, and the remainder is considered an idle memory, left to the next malloc use.

2. If there is no suitable free memory in malloc, then the program break will be moved as usual, or the new memory may be requested (there might be a surplus on the last mapping and there would be no need to remap).

Knowing these basic implementations, we found that malloc (), free () is a more dangerous function, so be careful when using the requested memory, especially at the boundary, otherwise the result can be catastrophic . For example, when using allocated memory, only 1 bytes are crossed out, and this byte is exactly the length of the other piece of memory, and when the memory is released, free maintains the wrong length, and the next time the memory is applied to malloc then a "disaster" comes.

The rest of the memory allocation functions

void *calloc (size_t nmemb, size_t size);

void *realloc (void *ptr, size_t size);

Calloc () is similar to malloc in that it allocates nmemb sizes to objects, but unlike malloc: Calloc initializes the allocated memory to 0.

ReAlloc () as the name of the "redistribution" means to adjust the size of the allocated memory PTR, if the memory is not enough after PTR will request a new area, the original memory is copied in the past, the newly added memory is not initialized. Therefore, the returned result may be different from PTR, in fact not in part. Therefore, realloc efficiency is not high enough. It is recommended not to use it when last resort.

void *alloca (size_t size);

The function is to allocate memory on the stack . This is described on the manual:

The Alloca () function allocates size bytes of space in the the stack frameof the caller. This temporary space was automatically freed when the function of the called ALLOCA () returns to its caller.

The need to allocate memory on the stack is not many scenarios, such as SETJMP,LONGJMP to perform a non-local jump when you need to use allocated memory, you should consider alloca, because the memory he requested is automatically released, so there will be no longjmp "bounce" when the memory leaks. Such a function is occasionally used in favor of physical and mental health.

Memory allocation in C language that's the thing.

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.