On the malloc function of C language and the problem of memory leak

Source: Internet
Author: User
Tags int size

malloc function

the prototype of the malloc function:

(void *) malloc (int size)

The return value of the malloc function is a null-type pointer, with a parameter of type int, that is, the amount of memory requested for allocation, in bytes. After the memory allocation is successful, the malloc function returns the first address of the memory, and you need a pointer to accept the address. However, because the return value of the function is a void * type, you must cast it to the type you are receiving. That is, what type of data will be used to store this memory in the future, such as char *p = (char *) malloc;

Allocates 100 bytes of memory on the heap, returns the first address of the memory, casts the address to the char * type, assigns the pointer variable p of the char * type, and tells us that this memory will be used to store the char type of data. That means you can only manipulate the memory through the pointer variable p. This memory itself has no name, access to it is anonymous access


Also note this with the malloc function: if the requested memory block is larger than the remaining memory blocks (whole blocks) on the current heap, the memory allocation fails and the function function is null. Note here that "the remaining memory block on the heap" is not the sum of all the remaining blocks of memory, because the malloc function requests a contiguous chunk of memory. Since the malloc function may not be successful in applying memory, we must verify that the memory allocation was successful with the if (NULL!= p) statement when using pointers to this memory.




Memory Leaks

In C language Program design, memory leak is almost difficult to avoid, C program to produce leaking memory, the running speed will gradually slow down, and eventually stop running; If the overwrite memory is generated, the program becomes very vulnerable and vulnerable to attack by a malicious user. Memory leaks are a hidden hazard, they are difficult to find, often not in the corresponding source code to find errors, need careful analysis and special detection tools to discover.

(1) The definition of memory leak

Usually what we call memory leaks is that the allocated memory is not released after use, no recycling, in the long run, will cause not enough memory to allocate. Generally, the longer the running time, the more memory consumed, which eventually leads to the system running. A typical memory leak is a leak of heap memory. Heap memory is that the program is allocated from the heap, of any size (the size of the memory block can be determined during the program run), and the memory must be explicitly freed after use. The application generally uses functions such as malloc,realloc,new to allocate a piece of memory from the heap, and after use, the program must be responsible for the corresponding call free or delete to release the memory block, otherwise, this piece of memory can not be reused, we say this memory leak.


(2) The reason of memory leak

2.1 C Language Memory allocation
In C, the memory space is divided into three areas, depending on the time (life cycle) of the data in memory:

1 Program Area : The code used to store the program, that is, the binary code of the program.

2 static storage : for storing global variables and static variables, the space for these variables is already allocated when the program is compiled.

3 Dynamic Storage : The memory allocated for program execution is divided into: Heap area (heap) and stack area (stack). Heap area: For dynamic memory allocation, when the program runs, the memory allocation function allocates memory on the heap. In the C language, only pointers can be used to dynamically allocate memory. Stack area: The memory area of a function's local variables and the storage unit of a function parameter when the function is executed, and the memory areas are automatically released when the function ends.
2.2 C language Dynamic memory allocation
Memory allocation functions are used in C language to dynamically allocate memory, these functions are: malloc () and realloc () functions. malloc (): You need to include the header file when you use this function. Use this function to specify the number of bytes of memory to allocate as parameters, such as:
int *pnumber= (int *) malloc (100)
This statement allocates 100 bytes of memory and assigns the address of the memory block to Pnumber, which can hold the maximum 25 int values, and each int occupies 4 bytes. If the requested memory cannot be allocated, malloc () returns a null pointer.
2.3 Free Dynamically allocated memory
The memory allocated on the heap is reclaimed by the operating system after the end of the entire application, but it is best to release it immediately after using the memory. If it is not released, it can cause memory leaks, greatly consuming system resources, and may result in various unknown errors. Therefore, the memory must be freed using the free () function, which is the memory address (pointer), for example, Pnumber, as in the previous example.

(3) method of memory leak avoidance

3.1 uses the malloc function correctly to allocate memory  
malloc is a function that is designed to allocate memory from the heap. Using the malloc function requires several requirements: Who to allocate memory to. How much memory is allocated. Do you have enough memory allocations? Data in what format memory will be used to store. Where is the allocated memory? If these 5 points are OK, then the memory can be allocated. Here's a look at malloc's prototype: (void *) malloc (int size)   The return value of the
malloc function is a null-type pointer with a parameter of type int, that is, the memory size of the request allocation, in bytes. After the memory allocation is successful, the malloc function returns the first address of the memory, and you need a pointer to accept the address. That is to say, what type of data will be used to store this memory in the future, such as:  
Char *p = (char *) malloc  
allocates 100 bytes of memory in heap memory, returns the first address of this memory, and casts the address to Char The * type is assigned to the pointer variable p of the char * type, and tells us that this memory will be used to store the char type data. You can only manipulate this memory through the pointer variable p, which has no name in itself and access to it anonymously. However, it is not necessarily possible for each malloc function to be allocated successfully to memory. Now that the MALLOC function requests memory for an unsuccessful possibility, we must use the IF (NULL) when using a pointer to this block of memory. = p) Statement to verify that the memory allocation did succeed.  


3.2 Use free function to release memory correctly
Since there is an allocation, it must have release, otherwise, the limited memory will run out, but not free memory is occupied space, and malloc corresponds to the free function. The free function has only one argument, which is the first address (pointer) of the memory block to be freed. In the previous example, free (p). The free function It does one thing: Cut off the pointer variable and the memory of the corresponding relationship. The free function is to cut off the relationship between this memory and P, and the value of P itself has not changed or disappeared, that is, the address that the pointer variable p itself saved has not changed, and the value saved in that block of memory has not changed. This is the function of the free function, a malloc corresponding to a free, is monogamous. After releasing the free (p) function memory, the address that the pointer variable p itself saved has not changed, so we must change the value of p to Null:p = NULL. If you do not leave the pointer null, the pointer becomes a "dangling pointer", which is dangerous and often a mistake.

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.