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 is the method of dynamic memory management in C language

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article, the editor introduces in detail "what is the method of dynamic memory management in C language". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "what is the method of dynamic memory management in C language" can help you solve your doubts. Let's follow the editor's ideas to learn new knowledge.

1. Why dynamic memory allocation is needed

On this question, let's take a look at how we opened up memory before.

Int val = 20 char arr / open four bytes on stack space char arr [10] = {0}; / / open up 10 bytes of contiguous space on stack space

But one problem that can be found is that no matter how we open up the memory space, its size has been specified before it is opened. Obviously, in practical applications, not all cases can know how much memory space he needs before the program is compiled. Maybe you want to say that it won't be long before you turn it up a little bit? But the waste of space caused by this is not what we want to see. So we have to try dynamic memory allocation.

two。 Introduction to dynamic memory functions 2.1 malloc and free

C language has provided us with a dynamic memory development function malloc.

Void* malloc (size_t size)

1. This function requests a continuously available space from memory and returns a pointer to that space.

two。 If the opening is successful, a pointer to the opened space is returned.

3. If opening fails, a NULL pointer is returned, so the return value of malloc must be checked.

4. The type of the return value is void*, so the malloc function does not know the type of opening up the space, which is decided by the user when using it.

5. If the parameter size is 0malloc, the behavior is standard and undefined, depending on the compiler.

Of course, where there is allocation, there will be release. C language also provides us with another function free, which is specially used for dynamic memory release and recycling. The function prototype is as follows.

Void free (void* ptr)

The 1.free function is used to free dynamically opened memory.

two。 If the space pointed to by the parameter ptr is not dynamically opened up, then the behavior of the free function is undefined.

3. If the argument ptr is a NULL pointer, the function does nothing.

We see the following example

# include int main () {int* ptr = NULL; ptr = (int*) malloc (num * sizeof (int)); if (NULL! = ptr) / / determine whether the ptr pointer is empty {int I = 0; for (I = 0; I < num; ipointer +) {* (ptr + I) = 0 }} free (ptr); / / release the dynamic memory pointed to by ptr ptr = NULL; return 0;}

I believe that this string of code can be understood when there are comments. But some careful readers may find that free (ptr) is followed by ptr=NULL. Why? In fact, after a piece of memory space is released, the pointer still points to the address of the released memory, and the ptr becomes a wild pointer. Once the program is called accidentally, it will cause the program to crash, so set it to NULL after the pointer is released to prevent this from happening.

2.2 calloc function

The calloc function is similar to malloc and is also used for dynamic memory allocation. The function prototype is as follows.

Void* calloc (size_t num, size_t size)

The function is to open up a space for num elements the size of size, and initialize each byte of the space to 0.

The only difference from the function malloc is that calloc initializes each byte of the requested space to all zeros before returning the address.

2.3 realloc function

Sometimes we find that the application space in the past is too small, and sometimes we think that the application space is too large, so for the sake of reasonable timing memory, we must make flexible adjustments to the memory size. Then the realloc function can adjust the memory size dynamically. The function prototype is as follows.

Void* realloc (void* ptr, size_t size)

Ptr is the memory address to be adjusted

New size after size adjustment

The return value is the adjusted starting position of the memory.

This function not only adjusts the size of the original memory space, but also moves the data in the original memory to the new space.

It is important to note that:

There are two situations when realloc adjusts memory space.

Case 1: there is enough space behind the original space

Case 2: there is not enough space behind the original space.

See the following illustration

Case 1

In case 1, to expand the memory, append the space directly after the original memory, and the data of the original space does not change.

Case 2

In case 2, when there is not enough space behind the original space, the way to expand is to find another contiguous space of the right size on the heap space to use. This function returns a new memory address.

In case 2, if the realloc is successful, the pointer to the original memory address becomes a hanging pointer, that is, the pointer points to a piece of memory that is not allocated to the user, and unexpected situations may occur if the pointer is used again, so pay special attention to this situation.

# include int main () {int* ptr = (int*) malloc (100); / / dynamic allocation int* p = NULL; p = (int*) realloc (ptr, 1000); / / reassign if (p! = NULL) / / determine whether it is successful {ptr = pbank / prevent dangling pointers} / / Business processing free (ptr) Set null after ptr=NULL;// release to prevent wild pointer return 0;}

Note that dynamic memory allocation should be as standardized as the above code.

3. Common dynamic memory errors 3.1 dereferencing NULL pointers

This point is no longer described too much, you can remember that dereferencing null pointers may cause all kinds of strange problems.

3.2 Cross-border access to dynamic opening up space

Like arrays, even dynamically opened spaces cannot be accessed out of bounds.

3.3.Use free release for non-dynamic open memory

Keep in mind that only dynamically opened memory can use free.

3.4.Use free to free up a portion of dynamically opened memory

See the following code

Void test () {int * p = (int *) malloc (100); paired memory; free (p); / / p no longer points to the starting position of dynamic memory}

Although some friends may think that since the free function frees memory according to pointers, can I partially free dynamically allocated memory by manipulating pointers? However, the dream is beautiful and the reality is very bony. If forced to do so, it will only lead to more unpredictable results.

3.5 release the same piece of dynamic memory multiple times

This mistake should not be made very often right now, but once you have a large amount of code later, you are likely to forget whether the memory has been freed, resulting in repeated bug.

Void test () {int * p = (int *) malloc (100); if (NULL! = p) {* p = 20;}} int main () {test (); while (1);}

Seeing this title and looking at this string of code, it should be easy for everyone to know that the above code forgot to release memory, resulting in a memory leak, but in fact, it is very easy for us to forget to open free after memory.

Forgetting to release dynamically opened space that is no longer in use can cause memory leaks.

Remember:

The space opened up dynamically must be released and released correctly.

After reading this, the article "what is the method of dynamic memory management in C language" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it before you can understand it. If you want to know more about related articles, welcome to follow the industry information channel.

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