Dynamically allocated Memory functions: malloc (), Calloc (), realloc (), and memset (), free () Detail Summary

Source: Internet
Author: User

The following information is mostly sourced from the network, and individuals are aggregated and added.

Memory can be divided into the following categories:


Stacking area (Stack): Automatically allocated and released by the compiler, the parameter values of the stored functions, local variables, temporary variables, and so on, they are obtained by the compiler automatically, the variable life length: The function ends to free memory.


Heap: Typically assigned and released by programmers, that is, programmers do not release, the end of the program may be recycled by the operating system (C + + has no such recycling mechanism, java/c#), note that it is different from the heap in the data structure, distribution is similar to the linked list.


Global Zone (Static zone): The storage of global variables and static variables is put together, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another adjacent area. Released by the system after the program is finished.


Literal constant: The constant string is placed here and released by the system at the end of the program.


Program code area: binary code that holds the body of the function.


The C standard function library provides a number of functions to implement memory management on the heap, including the malloc function, the free function, the Calloc function, and the ReAlloc function. Use these functions to include the header file stdlib.h. Their declarations are as follows:


void * malloc (int n);
void free (void * p);
void *calloc (int n,int size);
void * ReAlloc (void * p,int n);

The above function is memory on the heap, Life cycle: Programmer Confederacy Life and Death, free () function end.


1. malloc function


The malloc function can obtain the memory space of a specified byte from the heap, and its function is declared as follows:


void * malloc (int n);

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory availabl E. To return a pointer to a type other than void , use a type cast on the return value. The storage space pointed to by the return value are guaranteed to being suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc , even if the amount of memory requested is small.


where parameter n is the number of bytes required to allocate. If the function succeeds, malloc returns the first address of the memory space where n bytes are obtained, or null if the function execution fails.

Because the type of the malloc function value is a void pointer, it is necessary to forcibly convert its value type to an arbitrary type pointer so that the memory space obtained from the heap can be manipulated by manipulating the type pointer.


It is important to note that the memory space allocated by the malloc function is uninitialized. (it is possible to apply to the memory space before being used, there is garbage data, the uninitialized program has a security risk)

Therefore, in general, when using this memory space, call another function memset to initialize it to full 0. The declaration of the Memset function is as follows:


void * memset (void * p,int c,int N);


The function can place the specified memory space in bytes to the specified character C. where P is the first address of the memory space to be zeroed, C is the value to set, and N is the byte length of the memory space being manipulated. If you want to clear 0 with memset, the variable C argument is 0.

The operation statements for the malloc function and the memset function are generally as follows:

 int  * p=null;p  = (int  *) malloc  (sizeof  (int   if  (P==null) printf ("Can ' t  get  memory!< Span style= "color: #000000;" >\n "); memset (P,  0 , siezeof (int ) );


Note: Heap memory obtained through the malloc function must be initialized using the Memset function. New in C + + is easier to use, 1. The memory size required for the data type is automatically calculated 2. Returns the corresponding type pointer value without the type cast.


2. Free () function

Memory space obtained from the heap after the program is finished, the system will not automatically release it (Java has garbage collection mechanism, will be automatically released, C + + does not), need the programmer to manage. At the end of a program, you must ensure that all the memory space obtained from the heap has been safely released, otherwise it will cause a memory leak.


The free function implements the ability to release memory. Its function declaration is:


void free (void * p);


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


However, the free function simply releases the pointer to the point where the memory pointed to can be used by someone else, and the pointer still points to the point where the pointer is a wild pointer, and if you manipulate the pointer at this point it will cause an unexpected error. The security practice is to set the value of the pointer to null after using the free function to release the space pointed to by the pointer.
The statements are as follows:


Free (p);
P=null;

A few points to note about the free function:

1. Call free to release the allocated memory, indicating that the memory can be used by others, that is, the other place after malloc, can be allocated to the memory

2. With regard to the free release of this memory, we can only consider the data in this memory to be dirty, that is, the following possibilities:

A or the original value

B is emptied to 0, depending on the platform and compiler processing

C has been assigned by others, has changed the value

3.free (P) a misunderstanding: free (p) after the pointer to the P is still the original memory address, just said to tell the system this memory can be applied by other programs, not to say the point of P to get rid of.

This is why free (p) has to add a P = NULL.

For example, the output: Hello (after release, you can also output the data that P points to memory. Only dangerous operation)

Note: Heap space allocated using the malloc function must be freed before the program ends.


3. calloc function


The function of the Calloc function is similar to the function of the malloc function, which allocates memory from the heap. Its function is declared as follows:


void *calloc (int n,int size);


The function return value is a void type pointer. If the execution succeeds, the function obtains a size X n byte space from the heap and returns the first address of the space. If execution fails, the function returns NULL.

When this function is significantly different from the malloc function, the memory space obtained by the CALLOC function is initialized, and its contents are all 0.

That

int * p=null;p= (int *)malloc(sizeof(int)); memset (P,  0, siezeof (int));


Same as this effect

int *p== (int *)calloc(1, siezeof (int));

The Calloc function is suitable for an array requisition space (which is automatically initialized), and the size can be set to the space length of an array element, and N is set to the capacity of the array.


Tip: The allocated memory of the CALLOC function also needs to be released on its own.


4. realloc function


The functions of the realloc function are richer than the malloc function and the Calloc function, and can implement memory allocation and memory deallocation functions, which are declared as follows:


void * ReAlloc (void * p,int n);


Where pointer p must be a pointer to the heap memory space, that is, a pointer to the space allocated by the malloc function, the Calloc function, or the 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 amount of space pointed before P, then. Keep the original state unchanged.

If n is greater than the amount of space pointed to by the original p:

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.

2. If the current block of contiguous memory is not long enough, look for a longer enough place, 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 = (int *) realloc (p,2048); This notation. It is possible that the memory address that P originally pointed to was lost after the realloc allocation failed.

Correct wording:

p = (int*)malloc(sizeof(int)* -);

memset (p,0,sizeof (int) *24);
Q= (int*)realloc(P,sizeof(int)* -);//extend p to memory space from 24int to 48 int if(q! = NULL)//realloc function executes successfully, p is released, q is new memory pointer { Free(P); P=NULL; }



Note: Using the malloc function, the memory space allocated by the CALLOC function and the ReAlloc function is freed using the free function or the null realloc function of the pointer argument.




Note: If you want to use the memory allocated by the REALLOC function, you must initialize its memory with the Memset function


The following points to note are:


Both the function malloc () and calloc () can be used to dynamically allocate memory space. The malloc () function has a parameter, that is, the size of the allocated memory space, and malloc retains a certain amount of space to record allocations when allocating memory, and the more times the allocations are allocated, the more space they occupy. In addition, depending on the malloc implementation strategy, malloc may allocate more space each time it is allocated than is actually required, and multiple allocations lead to more of this 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, respectively, is the size of the memory space to allocate. If the call succeeds, they will return the first address of the allocated memory space.
The main difference between the function malloc () and Calloc () is that the former cannot initialize the allocated memory space, while the latter can.
ReAlloc () can expand or shrink the space indicated by a given pointer, whether it expands or shrinks, and the contents of the original memory will remain unchanged. Of course, for shrinking, the content of the part that is shrunk is lost.
ReAlloc () does not guarantee that the adjusted memory space and the original memory space remain the same memory address, whereas the pointer returned by Relloc is likely to point to a new address. So in the code, we have to reassign the return value of Relloc to p:p= (int *) realloc (p,sizeof (int) *15);

Dynamically allocated Memory functions: malloc (), Calloc (), realloc (), and memset (), free () Detail Summary

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.