C language memory allocation, C language allocation

Source: Internet
Author: User

C language memory allocation, C language allocation
Memory Structure of C program

The complexity of C language means that its memory model is indispensable. Unlike some advanced languages, you only need to use new to create an object. You don't need to worry about all the subsequent things. For C language, you must be familiar with all memory-related things. Otherwise, you will always step on thunder for a long time. Is a typical C program memory structure, of course there is an important premise, such a layout is inVirtual MemoryIn:

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 requests a 100-byte memory from the kernel, which is actually mapped to a memory page. Row 4 accesses the last 4 bytes of the Memory Page and is rewritten, the memory outside the access ing relationship of Row 6 is obviously invalid, and the program running result is as follows:

$ A. out

**
Segmentation fault

When the memory is released with brk ()/sbrk (), the ing relationship may not be immediately removed. When the program break drops more than one page, it is possible to return the applied physical memory to the kernel. Of course, all the operations on this memory after the release are undefined, which is the same as playing with fire. In addition, note that the position of program break cannot be moved outside the heap area, such as the bss area and data area, such behavior is basically an act of death.

Use C standard library functions

Malloc ()/free () is definitely one of the most widely used functions in C language. Compared with brk ()/sbrk (), its interface is simpler, and the memory can be freely released. (Brk ()/sbrk () cannot be released at will because when the program break moves down to release the memory, it will also release the "innocent" element on the top .) For example, in this case (the memory ing is removed here ):

The free () release does not have such a "pitfall", because the free release of memory may not necessarily move the program break. If there is still no memory to be released above the free () memory (high memory address), the program break will not be moved, so the ing relationship will not be removed, that is to say, the memory is not returned to the kernel. Instead, the idle memory is handed over to free maintenance. When the next malloc application is made, this memory (if enough) is returned to malloc. So how does free know the size of the released memory? This is because the memory returned by malloc has a special structure:

 

The size of the memory is recorded before the memory. When this memory is recycled, its length and address are recorded. When malloc is used again, it compares whether the idle memory list has the required memory and submits it to the program for "secondary use" (or N times ). Of course, the use of memory that does not use the idle memory list depends on the specific situation:

1. If the available memory is larger than that applied for by malloc, a part of the memory will be cut and returned to malloc. The remaining part will be regarded as a piece of idle memory, which will be reserved for the next malloc.

2. if there is no suitable idle memory in malloc, the program break will be moved as usual, and a new memory may be applied for (there may be surplus in the previous ing, you do not need to remap ).

After knowing these basic implementations, we find that malloc () and free () are dangerous functions,Be careful when using the applied memory, especially the boundary. Otherwise, the result may be disastrous.. For example, when the allocated memory is used, only one byte is exceeded, and this Byte records the length of the other memory. When this memory is released, free maintains the length of the error, and the next "disaster" will occur when you submit the memory to malloc when you apply for the memory.

Other memory allocation functions

    void *calloc(size_t nmemb, size_t size);

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

Like malloc, calloc () allocates nmemb objects of size, but unlike malloc, calloc initializes the allocated memory to 0.

Realloc (), as the name means "Reallocation", is used to adjust the size of the allocated memory ptr. If the memory after ptr is insufficient, a new area will be applied, the original memory is copied without initialization. Therefore, the returned results may be different from ptr. In fact, they are different in some cases. Therefore, the realloc efficiency is not high enough. We recommend that you do not use it when you have.

 

    void *alloca(size_t size);

The role isStackAllocate memory on. Manual is described as follows:

The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.

There are not many scenarios to allocate memory on the stack. For example, when setjmp and longjmp need to use the allocated memory for non-local redirection, alloca should be considered, because the memory he applied for is automatically released, there will be no memory leakage during longjmp "back-to-Hop. The occasional use of such functions is still beneficial to physical and mental health.

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.