Difference between malloc () and calloc () and memset ()

Source: Internet
Author: User

When programming C/C ++, programmers need to have a better understanding of the memory. The memory that often needs to be operated can be divided into the following categories:

STACK: automatically assigned and released by the compiler, stored function parameter values, local variables, temporary variables, and so on. The methods they are obtained are automatically executed by the compiler.
Heap, java/C #). Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
Global (static): the storage of global and static variables is put together, and the initialized global and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. The program is released by the system.
Text constant area: the constant string is placed here, and is released by the system after the program ends.
Code area: stores the binary code of the function body.
The C standard function library provides many functions to manage the memory on the stack, including the malloc function, free function, calloc function, and realloc function. To use these functions, you must include the header file stdlib. h. Their declaration is as follows:

Void * malloc (int n );
Void free (void * P );
Void * calloc (int n, int size );
Void * realloc (void * P, int N );
1. malloc Function

The malloc function can obtain the memory space of a specified byte from the stack. Its function declaration is as follows:

Void * malloc (int n );

The parameter n is the number of bytes to be allocated. If the function is successfully executed, malloc returns the first address to obtain the memory space. If the function fails to be executed, the return value is null. Because the malloc function value type is void pointer, you can convert the value type and assign it to any type pointer, in this way, you can operate on the memory space obtained from the stack by operating on this type of pointer.

Note that 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 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, C is the value to be set, and N is the byte length of the memory space to be operated. 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 ));

Note: The heap memory obtained through the malloc function must be initialized using the memset function.

Sample Code:

 
2. Free Function

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. For example, memory leakage occurs in the demo above.

The free function can release the memory. The function declaration is:

Void free (void * P );

Because the form parameter is a void pointer, the free function can accept any type of pointer arguments.

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 this 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. Therefore, for the demo above

Add the following two statements before the statement:

Free (P );

P = NULL;

Note: The heap space allocated by using the malloc function must be released before the end of the program.

3. calloc Function

The functions of the calloc function are similar to those of the malloc function, and the memory is allocated from the heap. The function declaration is as follows:

Void * calloc (int n, int size );

The Return Value of the function is a void pointer. If the execution succeeds, the function obtains the size x n Bytes from the stack and returns the first address of the space. If the execution fails, the function returns NULL. A significant difference between this function and the malloc function is that the memory space obtained by the calloc function is initialized and its content is all 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.

Sample Code

Tip: the memory allocated by the calloc function also needs to be released by itself.

4. realloc Function

The realloc function provides more functions than the malloc function and calloc function, and can implement memory allocation and memory release. Its function declaration is as follows:

Void * realloc (void * P, int N );

The pointer P must be a pointer to the heap memory space, that is, a pointer to the space allocated by the malloc function, calloc function, or realloc function. The realloc function changes the size of the memory block pointed to by the pointer P to n Bytes. If n is less than or equal to the size of space pointed to before P, then. Keep the original status unchanged. If n is greater than the size of the space pointed to before P, the system will allocate a new memory space of N for P from the heap. At the same time, copy the content that originally points to the space to the new memory space in sequence, and the space that previously points to P is released. The space allocated by the relloc function is not initialized.

Note: the memory space allocated by the malloc function, calloc function, and realloc function must be released using the free function or the realloc function with NULL pointer parameter.

Sample Code:

Note: To use the memory allocated by the realloc function, you must use the memset function to initialize its memory.

The following points should be noted:

Both the malloc () and calloc () functions can be used to dynamically allocate memory space. The malloc () function has a parameter, that is, the size of the allocated memory space. When allocating memory, malloc reserves a certain amount of space to record the allocation. The more times it is allocated, these records occupy more space. In addition, according to the different implementation policies of malloc, each allocation of malloc may allocate more space than actually required. Multiple allocation may lead to more such waste. Of course, these are related to the implementation of malloc. The calloc () function has two parameters: the number of elements and the size of each element, the product of these two parameters is the size of the memory space to be allocated. If the call is successful, the first address of the allocated memory is returned.
The main difference between the malloc () and calloc () functions is that the former Cannot initialize the allocated memory space, while the latter can.
Relloc () 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.
Relloc () does not guarantee that the adjusted memory space is the same as the original memory space address. On the contrary, the pointer returned by relloc is likely to point to a new address. Therefore, in the code, we must re-assign the returned value of relloc to P: P = (int *) relloc (p, sizeof (INT) * 15 );

The difference between malloc () and calloc () and memset () (17:08:29)
Tags: Miscellaneous
Process requests to dynamic memory are considered as not urgent. For example, when the executable file of a process is installed, the process does not necessarily access all the code immediately. Similarly, when a process calls malloc () to request dynamic memory, it does not mean that the process will soon access all the obtained memory. Therefore, the kernel always tries its best to delay the dynamic memory allocation for user-State processes.
Malloc ()
-------------------------------------------
The malloc () function is used to allocate memory: Pass the total number of bytes required as a parameter to the function. The returned value is a pointer to the latest memory allocation. If the memory is not allocated properly, the return value is null.
The Usage Technology of malloc:
Some_type * pointer;
Pointer = malloc (count * sizeof (* pointer ));

Note:
(1) This method ensures that malloc () allocates the correct amount of memory without considering the pointer's life. If the pointer type changes later, the sizeof operator automatically ensures that the number of bytes to be allocated is still correct.
(2) The memory returned by malloc () is "not initialized. This memory may contain any random garbage. You can use valid data immediately or at least use zero to initialize this memory. Initialize with 0. You can use
Void * memset (void * s, int C, size_t N );
(3) malloc () original data in the physical memory obtained by page missing exception in most cases, which is 0 (but cannot be guaranteed to be 0)

Calloc ()
-------------------------
The calloc () function is a simple package of malloc. Its main advantage is to clear the dynamically allocated memory.
Void * calloc (size_t nmemb, size_t size );
Experienced programmers prefer to use calloc (), because in this case, there will be no problems with the newly allocated memory content, and the call of calloc () will certainly clear 0, and avoid calling memset ().
 
Memset
Function: set all the content of each byte in the memory to the ASCII value specified by CH,
The block size is specified by the third parameter. This function usually initializes the newly applied memory.
Usage: void * memset (void * s, char CH, unsigned N );
Program example:
# Include <string. h>
# Include <stdio. h>
# Include <mem. h>
Int main (void)
{
Char buffer [] = "Hello world \ n ";
Printf ("buffer before memset: % s \ n", buffer );
Memset (buffer, '*', strlen (buffer ));
Printf ("buffer after memset: % s \ n", buffer );
Return 0;
}
Output result:
Buffer before memset: Hello World
Buffer after memset :***********
Compilation platform:
Microsoft Visual C ++ 6.0

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.