In-depth understanding of C pointer 2: C memory management, deep understanding of Memory Management

Source: Internet
Author: User

In-depth understanding of C pointer 2: C memory management, deep understanding of Memory Management

  Memory ManagementIt is important for all programs. Sometimes the memory is implicitly managed by the runtime system, such as automatically allocating memory for variables. In this case, the variable is allocated to the stack frame of the function in which it is located (each function has its own stack frame, which is used to save its local variables and return addresses ). If it is a static or global variable and the memory is in the Data Segment of the program, it is automatically cleared. A data segment is a memory area different from other data managed by the executable code and runtime system.

C language is also supportedDynamicMemory Management, the object is the memory allocated from the stack. This is implemented manually using the allocation and release functions. This process is called dynamic memory management. The basic steps for dynamic memory allocation in C are as follows:

1. Use malloc functions to allocate memory;

2. Use the memory to support applications;

3. Use the free function to release the memory.

int* pi = (int*) malloc (sizeof(int));*pi = 5;printf(" pi is : %d\n address : %p\n", *pi, pi);free(pi);// pi is : 5// address : 0x8843008

The parameter of the malloc function specifies the number of bytes to be allocated. If the operation succeeds, the pointer of the memory allocated from the stack is returned. If the operation fails, a null pointer is returned. The sizeof operator can determine the correct number of bytes to be allocated in the host system, because the number of bytes of data may be different in different systems. Each time you call malloc or similar functions, the corresponding free function call should end with to prevent memory leakage.

If the allocated memory is no longer used but it is not releasedMemory leakageMemory leakage may occur as follows:

1. Memory Address Loss;

2. The free function should be called but not called (implicit leakage );

Below:Memory Allocation FunctionIt can be used to manage dynamic memory, most of which are included in the stdlib. h header file:

1. malloc: allocate memory from the stack

2. realloc: based on the previously allocated memory block, realloc the memory to a larger or smaller part.

3. calloc: allocates memory from the stack and clears it

4. free: return the memory block to the heap.

The dynamic memory is allocated from the heap. For a series of memory allocation calls, the system does not guarantee the memory sequence and the continuity of the allocated memory. However, the allocated memory is aligned according to the pointer data type. For example, a 4-byte integer is allocated to the address boundary that can be divisible by 4. The address returned by the heap manager is the lowest byte address.

  Malloc FunctionAllocate a block of memory from the stack. The number of allocated bytes is determined by the unique parameter. The returned value is the void pointer. If the memory is insufficient, NULL is returned. This function does not clear or modify the memory, so the newly allocated memory contains junk data.

void* malloc(size_t);

Executing the malloc function will perform the following operations:

1. allocate memory from the stack;

2. The memory will not be modified or cleared;

3. Return the first byte address;

The void pointer can be converted to any pointer, but the displayed pointer type conversion provides better compatibility with c ++ and clearer code. Note that the sizeof operator should be used as much as possible for function parameters, and do not try to introduce a pointer variable that does not initialize memory data.

int* mpi = (int*) malloc (sizeof(int));
if(mpi!=NULL){//pointer OK}else
{//pointer not OK}

When initializing static or global variables, you cannot call the dynamic memory allocation function. However, for static variables, you can use a separate value assignment statement to allocate memory to the variables.

static int* spi;spi =  (int*) malloc (sizeof(int));

UseCalloc FunctionThe memory is cleared at the same time. Clearing the memory means to set its content to a binary value of 0.

void* calloc(size_t numElements, size_t elementSize);

The calloc function allocates memory based on the product of two parameters and returns a pointer to the first byte of memory. If the memory cannot be allocated, NULL is returned. The execution of calloc may be slower than that of malloc because it requires additional memory cleanup.

You can useRealloc Function.

void* realloc(void* ptr, size_t size);

The first parameter is the pointer to the original memory, and the second parameter is the request size. The returned value is a pointer to the re-allocated memory. If the requested new memory size is smaller than the original size, the excess memory will be returned to the heap. If it is larger than the original one, a new memory will be allocated next to the currently allocated memory area. Otherwise, the new memory will be allocated in other areas of the heap and copied to the new area. If the request size is 0, the memory is released. If no allocation is available, a null pointer is returned. Do not use addresses that exceed the memory allocation.

UseFree FunctionReturn unused memory to the system.

void free(void* ptr);

The pointer parameter should point to the memory allocated by the malloc function, and the memory will be returned to the heap. Although the pointer still points to the memory, the memory is considered to contain junk data and may be written into new data. This pointer is called a lost pointer. Note that the NULL pointer does not point to anything, and the lost pointer still points to an address. If the memory is allocated in a function, it should be released in the same function.

  Repeated releaseThe same memory is released twice. The second call to free will cause a running exception. The two pointers direct to the same memory addressAlias. Aliases may be released repeatedly.

The heap manager may not necessarily return the memory to the operating system after the free function, but may be used by the program later.

Lost pointerRefers to the pointer to access the released memory. Using a lost pointer can lead to unpredictable behavior and potential security risks. When the pointer alias is used, the lost pointer is more difficult to detect.

int *gpi;{int tmp = 5;*gpi = &tmp;}

Most compilers regard block statements as a stack frame. When the block statement exits, the tmp allocated on the stack frame will go out of the stack, and gpi will become a lost pointer pointing to a memory that has been automatically recycled.

In addition to using functions to manually allocate memory, there are also some non-standard technologies that can be used to achieve dynamic memory management of C. The key feature of these technologies is the automatic release of memory. When the memory is no longer used, it will be collected for backup, and the released memory will become garbage. Therefore, this process is also called garbage collection. Garbage collection frees programmers from worrying about how to release memory and focus more on the program itself. Garbage collection technology includes RAII and exception handling.

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.