Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does dynamic memory management in C language mean?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail the meaning of dynamic memory management in C language. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

I. dynamic memory allocation

(1) allocate memory with the function of malloc class

(2) use this memory to support applications

(3) use the free function to free memory.

There are three major operations in short answer to memory: allocation-use-release

Memory management refers to: allocation-release

The program code we wrote: using the

The essence of the program is to process data, and the data information needs to be stored in memory, that is, the break represented by the diode represents the binary number, and the binary number is further used to represent everything: such as music, text, video, pictures, and other resources.

Allocation-release: in order to make better use and recovery of memory resources, maximize the use of computing resources, a unified operating system to schedule

Dynamic memory allocation is actually about automatic memory allocation.

Automatic allocation: memory is actually the memory that the variables we define in the programming file are actually mapped at run time, and the memory of these variables is automatically managed (allocated-released) by the system. The variables in the function body (or statement block) are all distributed in the function frame, which is inserted into the function stack at runtime. The memory is allocated by the system, and the memory is reclaimed by the operating system. Consistent to the main function off the stack, the program exits.

Dynamic allocation: we manually apply for the memory allocated to our programs by the operating system, the memory area is mainly on the heap, and this part of the resources are manually applied for and recycled. The resources allocated are the places where we operate and store the data.

In fact, the variables we define will eventually be translated into addresses, all of which manipulate the values of variables through addressing (see assembly language)

# include # include int main (void) {int*pi= (int*) malloc (sizeof (int)); * pi=5; printf ("* pi:%d\ n", * pi); free (pi); return 0;}

Pay attention

Int * pi= (int) malloc (4)

However, depending on the memory model used by the system, the length of integers may change. The portable approach is to use the sizeof operator so that the correct length is returned no matter where the program runs.

Use (int) malloc (number * (sizeof (int); *

Second, dynamic memory allocation function

There are several memory allocation functions that can be used to manage dynamic memory, and although the specific functions available depend on the system, most systems have the following functions in their stdlib.h header files:

Malloc ()

Realloc ()

Calloc ()

The function describes how malloc allocates memory from the heap realloc on the basis of the previously allocated memory blocks, reallocates memory into larger or smaller parts calloc allocates memory from the heap and clears 1, malloc ()

The malloc function allocates a block of memory from the heap, the number of bytes allocated is specified by the function's only argument, and the return value is a void pointer. If there is not enough memory, it returns NULL. This function does not empty or modify memory.

Declaration: void* malloc (size_t)

(1) allocate memory from the heap

(2) memory will not be modified or emptied.

(3) return the address of the first byte.

Example usage: int* pi= (int*) malloc (sizeof (int))

Because malloc returns NULL when it cannot allocate memory, it is a good idea to check NULL before using its returned pointer, as shown below:

Int*pi= (int*) malloc (sizeof (int)); if (pirated pointer null) {/ / pointer is fine} else {/ / invalid pointer}

(4) static, global pointer and malloc

Functions cannot be called when static or global variables are initialized. The following code declares a static variable and attempts to initialize it with malloc:

* static int pi = malloc (sizeof (int))

This produces a compile-time error message, as do global variables.

For static variables, you can avoid this problem by allocating memory to the variables later with a separate statement. However, global variables cannot use separate assignment statements, because global variables are declared outside the function and executable code, and code such as assignment statements must appear in the function:

Static int * pi

Pi = malloc (sizeof (int))

2. Realloc ()

Statement: void * realloc (void * ptr,size t size)

The realloc function returns a pointer to a block of memory. This function takes two arguments, the first is a pointer to the original memory block, and the second is the size of the request. The reassigned block size is different from the block size referenced by the first parameter. The return value is a pointer to the reallocated memory.

The first parameter, the second parameter behavior, null malloc non-empty 0 original memory block is released non-empty than the original memory block using the current block allocation is smaller than the original memory block is larger than the original memory block either in the current location or in other locations

The heap manager can reuse the original block of memory without modifying its contents. However, the program continues to use more than 8 bytes of memory requested. That is, we did not modify the string so that it could fit into an 8-byte block of memory. In this case, we should have adjusted the length of the string so that it could fit into the reallocated 8 bytes. The easiest way to do this is to assign NUL to address 507. It is not a good practice to actually use more memory than is allocated and should be avoided.

3. Calloc ()

The calloc function empties memory when requesting memory [emptying memory means setting its contents to binary 0]

Declaration: void * calloc (size_t numElements,size_t elementSize)

The calloc function allocates memory based on the product of the two parameters numElements and elementSize and returns a pointer to the first byte of memory. If memory cannot be allocated, NULL is returned. This function was originally used to assist in allocating array memory.

If numElements or elementSize is 0, calloc may return a null pointer. If calloc cannot allocate memory, a null pointer is returned, and the global variable errno is set to ENOMEM, which is a POSIX error code that may not be available on some systems.

Third, use free function to free memory

With dynamic memory allocation, programmers can return memory that is no longer in use to the system, thus freeing memory

Save it for other purposes. This is usually done with the free function, which is based on the following prototype:

Statement: void free (void * ptr)

The pointer argument should point to the address of the memory allocated by the malloc class function, which is returned to the heap. Although the pointer still points to this area, we should think of it as pointing to junk data. You may later reallocate this area and load it into different data.

Keystone

Release meaning: refers to releasing the applied memory on the heap, which actually tells the heap manager that I don't need this resource and can be recycled.

However, the address of the memory requested before is retained locally, which we should avoid using, that is, setting the pointer to NULL.

Can no longer pick up the value of the released resource pointer

The memory pointed to by the pointer cannot be released multiple times (free)

Fourth, lost pointer

If memory has been freed and the pointer is still referencing the original memory, such a pointer is called a lost pointer. The stray pointer does not point to a valid object, which is sometimes referred to as premature release.

Problems caused by the lost pointer:

If memory is accessed, the behavior is unpredictable

If the memory is not accessible, it is a segment error

Potential security risks.

The reasons for this:

Access to freed memory

The returned pointer points to the automatic variable in the last function call

/ / in the first case, int*pi = (int*) malloc (sizeof (int)); printf ("* pi:%d\ n", * pi); free (pi); * pi = 10 pi / int*p1 = (int*) malloc (sizeof (int)); * p1 = 5pi * p2 = p1 (p1); * p2 = 10; / lost pointer / / third case / * most compilers treat block statements as a stack frame. The tmp variable is assigned to the stack frame, and then the stack is thrown when the block statement exits. The pi pointer now points to an area of memory that may eventually be overwritten by other active records, such as the foo function. Figure 2-13 illustrates this situation. * / int * pi;int tmp = 5x pi = & tmp;// where pi becomes a lost pointer foo ()

This is the end of the article on "what is the meaning of dynamic memory management in C language". I hope the above content can be helpful to you, so that you can learn more knowledge. If you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report