Malloc/calloc/realloc/alloca Memory Allocation Function

Source: Internet
Author: User

Calloc (), malloc (), realloc (), free (), alloca ()

The memory area can be divided into Stack, heap, static storage area and constant storage area, local variables, function parameters, and temporary variables all get the memory on the stack, they are obtained automatically by the compiler.
Using pointers, we can process memory addresses like assembly languages. The C standard function library provides many functions to manage the memory on the stack, including: malloc function, free function, calloc and realloc functions. To use these functions, you must include the header file stdlib. h.

There are differences and connections between the four functions. We should learn to grasp this relationship to compile a refined and efficient program.

Before explaining the specific meanings of these functions, we should first understand them literally. The first three functions share a common feature, that is, they all carry the character "alloc", that is, "allocate ", "Allocation" means allocate enough memory to the object. "calloc ()" is "allocate memory to multiple objects", "malloc () "is" allocating memory to an object "," realloc () "is" re-allocating memory." "Free ()" is relatively simple. "release" means to release the previously allocated memory.

Void * calloc (size_t nobj, size_t size );

Allocate enough memory to an array consisting of nobj objects of size and return the first byte pointer to the allocated area;
If the memory is not enough, null is returned. The initialization size of the space is 0 bytes.
Char * P = (char *) calloc (100, sizeof (char ));


Void * malloc (size_t size );

Allocate enough memory to the size object, and return the pointer to the first byte in the allocated area;
If the memory is insufficient, null is returned. The allocated space is not initialized.
Char * P = (char *) malloc (sizeof (char ));


Void * realloc (void * P, size_t size );

Change the object size pointed to by P to size byte.
If the newly allocated memory is larger than the original memory, the content of the original memory remains unchanged and the added space is not initialized.
If the newly allocated memory is smaller than the original memory, the new memory retains the content of the original memory, and the added space is not initialized.
Returns the pointer pointing to the new allocated space. If the memory is insufficient, null is returned, and the memory area pointed by the original p remains unchanged.
Char * P = (char *) malloc (sizeof (char ));
P = (char *) realloc (p, 256 );


Void free (void * P );

Releases the memory space pointed to by P. When P is null, it does not work.
P must call calloc, malloc, or realloc first.


Note the following five points:

(1) The heap memory obtained through the malloc function must be initialized using the memset function.

The memory space allocated by the malloc function is not initialized. Therefore, when using this memory space, you need to call another function memset to initialize it to all 0. The declaration of the memset function is as follows: void * memset (void * P, int C, int N );

This function can specify the single-byte location of the specified memory space as the specified character C, where p is the first address of the memory space to be cleared, and C is the value to be set, N indicates the length of the operated memory space in bytes. If you want to use memset to clear 0, the real parameter of variable C must be 0.

The operation statements of the malloc and memset functions are generally as follows:

Int * P = NULL;

P = (int *) malloc (sizeof (INT ));

If (P = NULL)

Printf ("can't get memory! \ N ");

Memset (p, 0, siezeof (INT ));

(2) The heap space allocated using the malloc function must be released before the program ends.

After the program ends, the system will not automatically release the memory space obtained from the stack. It needs to be managed by the programmer. At the end of a program, ensure that all the memory space obtained from the stack has been safely released. Otherwise, memory leakage may occur.

We can use the free () function to release the memory space. However, the free function only releases the content pointed to by the pointer, And the pointer still points to the original place. At this time, the pointer is a wild pointer, if you operate the pointer at this time, unexpected errors will occur. The safe practice is to use the free function to release the space pointed to by the pointer and set the pointer value to null.

(3) The Memory allocated by the calloc function also needs to be released independently.

The functions of the calloc function are similar to those of the malloc function. Memory is allocated from the heap. A significant difference between the calloc function and the malloc function is that the memory space obtained by the calloc function is initialized, the content is 0. The calloc function is suitable for applying space for arrays. You can set the size to the length of the array elements and N to the size of the array.

(4) If you want to use the memory allocated by the realloc function, you must use the memset function to initialize its memory.

The realloc function provides more functions than the malloc function and calloc function, allowing for memory allocation and memory release. Realloc can expand or contract the space indicated by the given pointer. Whether it is expansion or reduction, the content in the original memory will remain unchanged. Of course, for downgrading, the contents of the reduced part will be lost. Realloc does not guarantee that the adjusted memory space is the same as the original memory space. Instead, the pointer returned by realloc is likely to point to a new address.

Therefore, in the code, we must re-assign the value returned by realloc to P:

P = (int *) realloc (p, sizeof (INT) * 15 );

Even if you pass a null pointer (0) to realloc, then realloc is equivalent to malloc.

Int * P = (int *) realloc (0, sizeof (INT) * 10); // allocate a brand new memory space,

This line serves exactly the same purpose:

Int * P = (int *) malloc (sizeof (INT) * 10 );

(5) alloca () Functions

Another function is also worth mentioning. This is alloca (). Its call sequence is the same as that of malloc, But it allocates storage space on the stack frame of the current function, rather than in the heap. Its advantage is that when a function returns, it automatically releases the stack frames it uses, so it does not have to worry about releasing space. The disadvantage is that some systems cannot increase the stack frame length after the function has been called, so they cannot support the alloca function. Despite this, many software packages still use the alloca function and many systems support it.

 

Conclusion: You must remember that only calloc can specify the number and size, and can initialize the allocated memory. Other functions do not initialize the memory. You need to call memset () by yourself () function.

 

Malloc/calloc/realloc/alloca Memory Allocation Function

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.