Memory allocations in C language malloc, Alloca, Calloc, malloc, free, realloc, SBR

Source: Internet
Author: User

C Language and memoryallocation 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. The stack memory allocation operation 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 functions related to memory applications are mainlyalloca,calloc,malloc,free,realloc,sbrk and so on. void * __cdecl  alloca( size_t );  Alloca is to request memory from the stack, so there is no need to release.void *malloc (size_t size); The memory allocated by malloc is in the heap, and there is noThe contents of the memory are initialized, so basically malloc is called after the function memset to initialize this part of the memory space. void *calloc (size_t numelements,size_t sizeofelement); Calloc will initialize this part of the memory, set to 0. void* realloc (void* ptr, unsigned newsize); ReAlloc the size of the memory requested by malloc. The requested memory eventually needs to be freed through the function free. char *sbrk (int incr);SBRK is to increase the size of the data segment;

Similarities and differences between Malloc,alloc,realloc

The declarations of the three functions are:
void* realloc (void* ptr, unsigned newsize);
void* malloc (unsigned size);
void* calloc (size_t numelements, size_t sizeofelement);
are in the Stdlib.h function library. Their return value is the address that the request system assigns, and returns NULL if the request fails.

The difference between malloc and calloc is 1 blocks from N blocks:
The malloc invocation form is (type *) malloc (size): Allocates a contiguous region of length "size" in the dynamic store of memory, returning the first address of the zone.
The Calloc invocation form is (type *) calloc (n,size): Allocates a contiguous region of length "size" bytes in the dynamic store of memory, returning the first address.
The ReAlloc invocation form is (type *) realloc (*ptr,size): Increases the PTR memory size to size. (You can also zoom out and shrink the content away).

Another thing that cannot be directly seen is that malloc allocates memory and does not initialize the resulting memory, so the value will be random in a new piece of memory. Calloc automatically initializes the memory space to zero after the dynamic allocation of memory.

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 and other functions similar to retail, to meet the requirements of the program run. This mechanism is similar to buffering. The reason for using this mechanism: system calls cannot support arbitrary-size memory allocations ( Some system calls only support a fixed size and its multiple memory requests, so that the allocation of small memory will cause waste; System call request memory is expensive and involves the conversion of user state and kernel mentality.

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 *sizeofele ment);

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.

ReAlloc has a detail to note:

is to expand the existing piece of memory.

char* p = malloc (1024);
char* q = realloc (p,2048);

The question now is what we should do with pointer p. Just start with my most intuitive understanding, if it is directly p = NULL;. In the end, you just need to free up the Q space.

Because I'm doing a package recently. Results are found when doing unit tests. Sometimes I'm in free (q); Will make a mistake. So I was depressed.

After careful follow-up, found realloc after the Q and P's pointer address is the same. But sometimes it's not the same.

Carefully checked the information. Get the following information:

1. If the current contiguous block of memory is sufficiently realloc, just expand the space pointed to by P and return the pointer address of P. This time Q and P point to the same address.

2. If the current block of contiguous memory is not long enough, look for a longer enough place to allocate a new memory, q, and copy the contents of p to Q and return Q. and remove the memory space that P points to.

This means that the realloc sometimes produces a new memory address, and sometime does not. So after the assignment is complete. We need to determine if p is equal to Q. and do the corresponding treatment.

A bit of attention here is to avoid P = realloc (p,2048); This notation. It is possible that the memory address that P originally pointed to was lost after the realloc allocation failed.

Memory allocations in C language malloc, Alloca, Calloc, malloc, free, realloc, SBR

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.