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

Source: Internet
Author: User

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 links between the four functions. We should learn to grasp this relationship to develop a refined and efficientProgram.

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. If the allocated memory block is initialized to 0, memset Initialization is not required. Experienced programmers prefer to use calloc (), because in this case, there will be no problems with the newly allocated memory content, and calling calloc () will certainly clear 0.

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 );

 

Detailed syntax description of realloc:

Void * realloc (void * memblock, size_t size );
1. If memblock = 0, size! = 0, Space allocated for null pointers, same as malloc (memblock, size)
2. If memblock! = 0, size = 0, Release allocated space, same as free (memblock)
3. If memblock! = 0, size! = 0, Indicates that the allocated space is re-allocated,
1) if the size is <the size of memory allocated by memblock, the back part of memblock is removed, and the returned pointer is equal to that of memblock.
2) if size> memory size allocated by memblock,
(1) and the memblock size is greater than or equal to the total free memory size, the memory size is allocated, and the returned pointer is equal to memblock.
(2) If the memblock size and the total free memory afterwards are smaller than the size, the memory size will be allocated elsewhere. The returned pointer and memblock are not equal. If there is not enough space to allocate memory elsewhere, null is returned.

 

Void free (void * P );

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

 

Note the following five points:

(1) PassMallocThe heap memory obtained by the function must be used.MemsetFunction Initialization 

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) UseMallocThe heap space allocated by the 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)CallocThe memory allocated by the 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 useReallocThe memory allocated by the function, which must be usedMemsetThe function initializes 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.

ThereforeCode, 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) AboutAlloca ()Function

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.

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.