BRK () system calls in Linux, Sbrk (), mmap (), malloc (), calloc () The similarities and differences "turn"

Source: Internet
Author: User
Tags goto

Transferred from: http://blog.csdn.net/kobbee9/article/details/7397010

The main work of BRK and SBRK is to implement virtual memory-to-memory mapping. In GNUC, memory allocations are:
Each process can access a virtual memory space of 3G, but at the time of program compilation, it is not possible or necessary to allocate such a large space for the program, only allocate not large data segment space, the dynamic allocation of space in the program is allocated from this piece. If this space is not enough, the malloc function family (realloc,calloc, etc.) calls the SBRK function to move the lower bound of the data segment, and the SBRK function maps the virtual address space to memory for use by the malloc function under the management of the kernel. (See Linux kernel scenario analysis)

#include <unistd.h>

int brk (void *end_data_segment);

void *sbrk (ptrdiff_t increment);

DESCRIPTION
BRK sets the end of the data segment to the value specified by End_data_segment, then that's value is Reas Onable, the system does has enough memory and the process does not exceed it max data size (see Setrlimit (2)).

SBRK increments the program's data space by increment bytes.   Sbrk isn ' t a system call, it's just a C library wrapper. Calling Sbrk with an increment of 0 can is used to find the current location of the program break.

RETURN VALUE
On success, BRK returns zero, and SBRK returns a pointer to the start of the new area. On error, 1 is returned, and errno are set to Enomem.


SBRK is not a system call, it is a C library function. System calls typically provide a minimum of functionality, and library functions often provide more complex functionality.

On Linux systems, when a program is loaded into memory, the kernel establishes code snippets, data segments, and stack segments for the user process address space, which is used for dynamic memory allocation between the data segment and the stack segment.

The member variables Start_code and End_code in the kernel data structure mm_struct are the starting and ending addresses of the process snippet, Start_data and End_data are the start and end addresses of the process data segment, and Start_stack is the process stack segment start address , START_BRK is the process dynamic memory allocation start address (the start address of the heap), and a BRK (the current last address of the heap), which is the current terminating address of the dynamic memory allocation.

The basic function of C language dynamic memory allocation is malloc (), and the basic implementation on Linux is called by the kernel's BRK system. BRK () is a very simple system call, simply changing the value of the member variable BRK of the MM_STRUCT structure.

The MMAP system call implements a more useful dynamic memory allocation function, which can map all or part of a disk file to a user space, and the process of reading and writing files becomes a read-write operation. The Do_mmap_pgoff () function in the Linux/mm/mmap.c file is the core of the MMAP system call implementation. The code for Do_mmap_pgoff () simply creates a new vm_area_struct structure and assigns the parameter of the file structure to its member variable m_file, and does not actually load the contents into memory.
One of the basic ideas of Linux memory management is to establish a physical mapping of this address only when actually accessing an address.

==================================================================================
C Language and memory allocation method
(1) Allocation from a static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.
(2) Create on the stack. When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. Stack memory allocation operation

The CPU is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.
(3) Allocation from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most

C Language and memory application related functions are mainly alloc,calloc,malloc,free,realloc,sbrk and so on. Where Alloc is requesting memory from the stack, so there is no need to release it. The memory allocated by malloc is in the heap and does not initialize the contents of the memory, so basically malloc calls the function memset to initialize this part of the memory space. Calloc will initialize this part of the memory, set to 0. ReAlloc, however, adjusts the size of the memory requested by malloc. The requested memory eventually needs to be freed through the function free. The SBRK is the size of the data segment;

Malloc/calloc/free is basically a C function library, which is not related to the OS. The C library internally uses a certain structure to save the current amount of available memory. If the size of the program malloc exceeds the space that is left in the library, then the BRK system call will be called to increase the available space first. And then allocate space. Free, the freed memory is not immediately returned to the OS, but remains in the internal structure. For example: BRK is similar to wholesale, a one-time application of large memory to the OS, and malloc functions like retail, to meet the requirements of the program runtime. This mechanism is similar to buffering.

Reasons for using this set of mechanisms: system calls cannot support arbitrary-sized memory allocations (some system calls only support a fixed size and a multiple memory request, so the allocation of small memory can be wasteful; the system call request memory is expensive and involves the conversion of the user state and the kernel mentality.
Both the function malloc () and calloc () can be used to allocate dynamic memory space, but the two are slightly different.
The malloc () function has a parameter that is the size of the memory space to allocate:
void *malloc (size_t size);
The Calloc () function has two parameters, each of which is the number of elements and the size of each element, and the product of these two parameters is the size of the memory space to allocate:
void *calloc (size_t numelements,size_t sizeofelement);
If the call succeeds, the function malloc () and Calloc () will return the first address of the allocated memory space.
The main difference between the malloc () function and the calloc () function is that the former cannot initialize the allocated memory space, while the latter can. If the memory space allocated by the malloc () function has not been used, then each of these may be 0, and conversely, if this portion of the memory space has been allocated, deallocated, and redistributed, then there may be a variety of data left behind. That is, when a program that uses the malloc () function starts (the memory space has not been reassigned) to work, it may cause problems after a period of time (the memory space has been reassigned).
The Calloc () function initializes each bit of the allocated memory space to zero, meaning that if you allocate memory for an element of a character type or integer type, those elements will be guaranteed to be initialized to zero, and if you are allocating memory for elements of pointer type, these elements are usually (but not guaranteed) are initialized to null pointers, and if you are allocating memory for elements of a real type, then these elements may (only in some computers) be initialized to 0 of the floating-point type.
Another point of difference between the malloc () function and the calloc () function is that the calloc () function returns an array of an object, but the malloc () function returns only one object. To make it clear that a memory space is allocated for an array, some programmers choose the calloc () function. However, in addition to initializing the allocated memory space, the vast majority of programmers consider the following two function invocation methods to be indistinguishable:
Calloc (numelements, sizeofelement);
malloc (numelements *sizeofelement);
One point to explain is that in theory (according to the Ansic standard) the arithmetic operations of pointers can only be performed in a specified array, but in practice, many C programs break through this limitation even if the C compiler or translator follows this rule. Therefore, although the malloc () function does not return an array, its allocated memory space can still be used by an array (as is the case with the realloc () function, although it cannot return an array).
In summary, when you choose between the Calloc () function and the malloc () function, you only need to consider whether you want to initialize the allocated memory space, regardless of whether the function can return an array.
A memory leak occurs when the program is running with malloc, but no free. Part of the memory is not used, but because there is no free, so the system thinks that this part of memory is still in use, resulting in continuous application of memory to the system, is the system memory is continuously reduced. However, A memory leak simply means that when the program is running, the OS will reclaim all of the resources when the program exits. Therefore, the proper re-start of the program, sometimes a bit of a function.

SBRK (int incr) This function is used to increase the amount of space allocated to the calling program's data segment, increasing the incr bytes of space BRK function's prototype is: int brk (void *endds)
Its function is to change the allocation of data segment space
Char *p;
P=malloc (1);
The size of the memory space that P points to is 1 byte
BRK (p+100)
At this point the size of the memory space P points to is 101 bytes

Program allocates virtual memory nor do you want a byte to give you a byte, but instead you want a byte to give you a page because the physical memory can only be mapped in pages. You want another byte when it gives you the rest of the space on this page.

Note that most of the UNIX virtual memory usage is only increased.

Code:malloc (+)--->;sbrk + = 32 * 1024
Free ()--->;sbrk does not decrease.
But if you do it again.
The malloc (>;SBRK)----also does not increase, using the original space.
But for Linux it is to shrink in the largest number of memory;

Code:<code>
A = malloc (* 1024x768)--&GT;;SBRK + = 32 * 1024
b = malloc (* 1024x768)--&GT;;SBRK + = 32 * 1024
if (* * *) {
Free (b); --->;sbrk-= 32 * 1024;
}
else{
Free (a); --->;sbrk is not reduced. Just a little more empty.
}
</code>
Code:<code>
/* Linux Kernel code */
BRK ()
/*
* SYS_BRK () for the most part doesn ' t need the global kernel
* Lock, except when a application is doing something nasty
* Like trying to un-brk a area the has already been mapped
* to a regular file. In this case, the unmapping would need
* To-Invoke file system routines that need the global lock.
*/
Asmlinkage unsigned long sys_brk (unsigned long BRK)
{
unsigned long rlim, retval;
unsigned long newbrk, oldbrk;
struct Mm_struct *mm = current->;mm;
Down_write (&mm->;mmap_sem);
if (BRK < Mm->;end_code)
Goto out;
NEWBRK = Page_align (BRK);
OLDBRK = Page_align (MM-&GT;;BRK);
if (oldbrk = = newbrk)
Goto SET_BRK;
/****** virtual memory here to shrink ******/
/* Always allow shrinking brk. */
if (BRK <= mm->;brk) {
if (!do_munmap (mm, NEWBRK, OLDBRK-NEWBRK))
Goto SET_BRK;
Goto out;
}
/* Check against Rlimit. */
Rlim = current->;rlim[rlimit_data].rlim_cur;
if (Rlim < rlim_infinity && brk-mm->;start_data >; Rlim)
Goto out;
/* Check against existing mmap mappings. */
if (find_vma_intersection (mm, OLDBRK, newbrk+page_size))
Goto out;
/* Check If we have enough memory. */
if (!vm_enough_memory (NEWBRK-OLDBRK) >;>; Page_shift))
Goto out;
/* Ok, looks good-let it rip. */
if (DO_BRK (OLDBRK, newbrk-oldbrk)! = oldbrk)
Goto out;
SET_BRK:
MM-&GT;;BRK = BRK;
Out
retval = mm->;brk; /**** This is the return value *****/
Up_write (&mm->;mmap_sem);
return retval;
}
</code>
In Linux, SBRK (0) can return more accurate virtual memory usage,
In SOLARIS/HP sbrk (0) returns the virtual memory usage in pages. Use SBRK (0) to return how much memory the program is currently using.

<code>
Main () {
int start,end;
Start = sbrk (0);
....
malloc (* *);
....
End = SBRK (0);
printf ("Hello I used%d vmemory", End-start);
}

</code

BRK () system calls in Linux, Sbrk (), mmap (), malloc (), calloc () The similarities and differences "turn"

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.