In-depth understanding of the C Pointer II: C Memory Management

Source: Internet
Author: User

  Memory management is important for all programs. Sometimes memory is implicitly managed by the runtime system, such as automatically allocating memory for variables. In this case, the variable is allocated on the stack frame of the function where it is located (each function has its own stack frame to hold its local variable and return address, etc.). In the case of static or global variables, memory is automatically zeroed out in the program's data segment. A data segment is an area of memory that differs from executable code and other data that is managed by the runtime system.

The C language also supports dynamic memory management, where the object is the memory allocated from the heap. This is implemented manually using the allocation and deallocation functions, which is known as dynamic memory management. The basic steps for dynamically allocating memory in C are:

1. Allocate memory with the function of malloc class;

2, using these memory support applications;

3. Use the free function to release memory.

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

The parameters of the malloc function specify the number of bytes to allocate. Returns a pointer to the memory allocated from the heap if successful, and a null pointer if it fails. The sizeof operator can determine the correct number of bytes that should be allocated in the host system, because the number of bytes in the data may be different in different systems. Each time a malloc or similar function is called, there should be a corresponding free function call at the end to prevent a memory leak.

A memory leak can occur if the allocated memory is no longer used but is not freed, and the memory leak may be as follows:

1, lost memory address;

2, should call the free function but not called (implicit disclosure);

The following memory allocation functions can be used to manage dynamic memory, most of which are contained in the Stdlib.h header file:

1. malloc: Allocating memory from the heap

2. ReAlloc: Reallocate memory to a larger or smaller portion based on previously allocated memory blocks

3. Calloc: Allocating memory from the heap and zeroing

4. Free: Returns a block of memory to the heap

Dynamic memory is allocated from the heap, and for a series of memory allocation calls, the system does not guarantee the order of memory and the continuity of the allocated memory. However, allocated memory is aligned according to the data type of the pointer, such as a 4-byte integer assigned to an address boundary that is divisible by 4. The address returned by the heap manager is the lowest-byte address.

  The malloc function allocates a chunk of memory from the heap, the number of bytes allocated is set by a unique parameter, the return value is a void pointer, and NULL is returned if there is not enough memory. This function does not empty or modify memory, so the newly allocated memory contains garbage data.

void* malloc (size_t);

The malloc function performs the following actions:

1, allocating memory from the heap;

2, memory will not be modified or emptied;

3, return the address of the first byte;

The void pointer can be converted to any pointer, but the displayed pointer-type conversion provides better compatibility with C + + and can make the code clearer. Note that the function arguments use the sizeof operator as much as possible, and do not attempt to fuse a pointer variable with uninitialized memory data.

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

Dynamic memory allocation function cannot be called when initializing static or global variables. For static variables, however, a separate assignment statement can be used to allocate memory to the variable.

Static int*=  (int*) malloc (sizeof(int));

Using the calloc function empties the memory while it is allocated. Emptying memory means to place its contents in binary 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 memory cannot be allocated, NULL is returned. The execution of calloc may be slower than malloc because it is doing additional memory cleanup work.

If you need to increase or decrease the memory allocated for pointers, you can use the realloc function .

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

The first parameter is a pointer to the original memory fast, and the second is the size of the request. The return value is a pointer to the memory that is being reassigned. If the requested new memory size is smaller than the original, the extra memory is returned to the heap. If larger than the original, it is possible to allocate new memory next to the currently allocated memory area, otherwise it will be allocated in other areas of the heap and the memory will be copied to the new zone. If the request size is 0, then the memory is freed. If it cannot be allocated, a null pointer is returned. Note Never use an address that exceeds the memory allocation.

Use the free function to return memory that is no longer in use to the system.

void free (void* ptr);

The pointer parameter should point to the memory allocated by the malloc function, which will be returned to the heap. Although the pointer still points to the memory, the memory is now considered to contain garbage data and may be written to new data. The pointer is called a stray pointer. Note that the null pointer does not point to anything, and the stray pointer still points to an address. If the memory is allocated within a function, then it should be released in the same function.

  Repeat release refers to releasing the same piece of memory two times. The second call to free throws a run-time exception. The two pointers point to the same memory address, which is called an alias . Aliases can cause duplicate deallocation.

The heap manager does not necessarily return memory to the operating system after the free function, but may later use it for the program.

A stray pointer is a pointer to a memory that has been freed. Using a stray pointer can cause unexpected behavior and potential security risks. In the case of pointer aliases, stray pointers are more difficult to detect.

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

Most compilers take block statements as a stack frame. When the block statement exits Yes, the TMP allocated on the stack frame is out of the stack, and the GPI becomes a stray pointer to a piece of memory that has been automatically reclaimed.

In addition to using functions to manually allocate memory, there are some non-standard techniques that can be used to implement dynamic memory management for C. The key feature of these technologies is the automatic release of memory. Once the memory is no longer in use, it is collected for backup and the freed memory becomes garbage, so this process is also called garbage collection. Garbage collection frees programmers from having to worry about when to release memory and focus more on the program itself. Garbage collection techniques include RAII and exception handling.

In-depth understanding of the C Pointer II: C Memory Management

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.