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

Example Analysis of dynamic memory Management in C language

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the example analysis of dynamic memory management in C language, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article.

What is dynamic memory allocation

We all know that in C language, when a variable is defined, the system allocates memory space for the variable, and this space is opened up on the stack, which has two characteristics.

The size of the open space is fixed.

When an array is declared, the length of the array must be specified to facilitate the allocation of memory for it

But this method can not meet our needs in development, because sometimes we need to open up the size of the space, only in the process of the program patrol to know how much to open up.

At this time, this way of opening up arrays can not be satisfied, so there is a need for dynamic memory allocation.

On the other hand, the dynamic memory allocation will allocate the space according to the demand, the size can be changed, and the space is allocated on the heap area, and half of the memory space of the heap area will be larger than the stack area.

Introduction of dynamic memory function

Dynamic memory management is required, and you need to understand the following functions in the C language.

Unified description: the following functions are included in.

Free

Void free (void* ptr)

In order to demonstrate the code later, let's first introduce the function free.

After we use the relevant function to dynamically open up the memory space, the function will return the first address of the space to the user. when the user runs out of space, he needs to release the space manually and return the memory space to the operating system.

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

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

The free space is the memory space that ptr points to.

In the first case above, it is possible that the compiler will report an error.

If we just open up space for use without releasing it, it will take up memory resources, cause memory leaks and affect performance.

Therefore, we need to form the good habit of releasing after use.

Malloc

Void* malloc (size_t size)

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

The feature of continuous availability, just like an array.

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

If the opening fails, a NULL pointer is returned.

The return value is of type void*, so users need to convert and use it according to their own needs.

If the parameter size size is 0, the behavior of remalloc is not specified by the flag, depending on the compiler.

The size of the size is in bytes.

# include int main () {/ / Code 1 int num = 0; scanf ("% d", & num); int arr [num] = {0}; / / Code 2 int* ptr = NULL; ptr = (int*) malloc (num * sizeof (int)); if (NULL! = ptr) / / determines whether the ptr pointer is empty {int I = 0 For (I = 0; I)

< num; i++) { *(ptr + i) = 0; } } free(ptr);//释放ptr所指向的动态内存 ptr = NULL;//是否有必要? return 0;} 上面的代码就是malloc函数的基本使用过程,在代码1中,这样的使用方法,一般来说编译器是不支持的,而第二种方法,也就是动态内存开辟的方法,编译器就支持。 在最后,记得要把ptr所指向的空间给释放掉。 这个时候,ptr种存储的仍然是那块空间的地址,这就称为了野指针,所以我们还要把ptr置空。 calloc 与malloc类相似的,C语言还提供了另外一个动态开辟内存的函数,那就是calloc。 void* calloc (size_t num, size_t size); 需要注意的是,这个函数的参数有所不同,第一个参数num是用来确定你开辟的连续空间是用来存放多少个元素的,而第二个参数size表示的是一个元素占用多少的字节。 函数的功能是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。 与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全0。 所以,如果我们需要在动态开辟内存的时候进行初始化,我们可以使用calloc这个函数。 我们可以通过调试的监视窗口来查看这个函数在开辟空间的时候是否帮我们初始化。 #include int main(){ int* p = (int*)calloc(10, sizeof(int)); if (NULL != p) { //使用空间 } free(p); p = NULL; return 0;}realloc 有时候我们会发现,哪怕是使用上面的动态内存管理的函数,也会有不方便的时候。我们可能会因为空间申请小了不够用而去扩容,但是如果我们使用上面两个函数去开辟更大的空间的时候,之前的数据拷贝过来新开辟的更大的空间又很麻烦。 这个时候,我们就可以使用realloc了。 void* realloc (void* ptr, size_t size); ptr 是要调整的内存地址。 size 调整之后新大小,和malloc一样,是以字节为单位的。 返回值为调整之后的内存起始位置。 这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新的空间。 在realloc函数使用的时候,会出现两种情况: 原有的空间之后还有足够的空间 如果原来的内存空间之后还有足够的空间来满足新的大小,这时候就会直接对原来的空间进行扩容,原来空间的数据不会发生变化。 原有的空间之后没有足够的空间 如果原来的空间之后没有足够的空间满足需要,就会在内存区域中开辟一片能够满足新的大小需要的连续空间,并且把原来空间的数据拷贝的新的空间中,释放原来的空间,返回新的地址。 #include int main(){ int* ptr = (int*)malloc(100); if (ptr != NULL) { //业务处理 } else { exit(EXIT_FAILURE); } //扩展容量 //代码1 ptr = (int*)realloc(ptr, 1000); //代码2 int* p = NULL; p = realloc(ptr, 1000); if (p != NULL) { ptr = p; } //业务处理 free(ptr); return 0;} 上述代码种,代码1的做法是不安全的,如果我们扩容失败后,会返回空指针,这个时候,ptr接收了空指针,就会造成ptr原来的那块空间的数据丢失,并且造成内存泄漏。 因此,一般我们都需要像代码2那样,先用一个临时的指针变量接收返回值,并且在判定不为空指针后再复制给ptr。 动态内存管理中常见的错误 我们在使上面这些函数的时候,会经常出现一下的错误。 对NULL指针的解引用操作void test(){ int* p = (int*)malloc(INT_MAX / 4); //没有进行判空,就直接使用空间 *p = 20;//如果p的值是NULL,就会有问题 free(p);}对动态开辟空间的越界访问void test(){ int i = 0; int* p = (int*)malloc(10 * sizeof(int)); if (NULL == p) { exit(EXIT_FAILURE); } for (i = 0; i i = 100;for (i = 0; i < 100; i++){ p->

A [I] = I;} free (p)

In this way, the flexible array member an is equivalent to obtaining the continuous space of 100 integer elements.

Advantages of flexible arrays

The above code can also be designed like this:

/ / Code 2typedef struct st_type {int I; int* sizeof;} type_a;type_a* p = (type_a*) malloc (sizeof (type_a)); p-> I = 100 int* malloc (p-> I * sizeof (int)); / / Business processing for (I = 0; I

< 100; i++){ p->

PAA [I] = I;} / / Free space free (p-> pyoga); p-> patela = NULL;free (p); p = NULL

Code 1 and code 2 above can accomplish the same function, but the implementation of method 1 has two benefits:

Facilitate memory release

This is good for access speed.

Thank you for reading this article carefully. I hope the article "sample Analysis of dynamic memory Management in C language" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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