21.C language dynamic memory management


In the C language, the program can not determine the time of writing memory size desirable in the process of running the program according to the allocation amount data size of the dynamic memory. Dynamic memory management, refers to the process of the program is running in dynamic applications and free up memory space.

C language programs allow dynamic memory management, open up at any time whenever the need arises released when not needed. Dynamic memory management is done by calling the library functions, mainly malloc and free
functions.

First, the relevant libraries

1, malloc function

Function prototype:

void *malloc(unsigned int size)

Malloc effect is to apply a size to the size of the system is a continuous memory space, if the request fails, the function returns 0 if successful, returns the starting address successfully allocated memory block.

E.g:

malloc(100)// 申请 100 个字节的临时分配域,返回值为其第一个字节的地址

malloc base type of the return value of the address is
void, i.e., does not point to any type of data, providing only one address, the program need to define a pointer to the memory address dynamically allocated.

E.g:

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

2, free function

Function prototype:

void free(void *p);

Action is the release of free pointer p pointing to dynamic memory space, p is the return address when calling function malloc, free function returns no value.

E.g:

free(pi);     // 释放指针变量pi指向的已分配的动态空间

Example (book107.c)

/*
 * 程序名:book107.c,此程序用于演示C程序动态内存管理。
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct st_girl  // 超女结构体
{
  char name[50];     // 姓名
  int  age;          // 年龄
};

int main(int argc,char *argv[])
{
  int    *pi=malloc(sizeof(int));    // 分配int类型大小的内存
  long   *pl=malloc(sizeof(long));   // 分配long类型大小的内存
  double *pd=malloc(sizeof(double)); // 分配double类型大小的内存
  char   *pc=malloc(101);            // 分配101字节的内存,可存放100个字符的字符串
  struct st_girl *pst=malloc(sizeof(struct st_girl)); // 分配struct st_girl结构体大小的内存

  // 以下代码是像普通指针和变量一样使用动态分配的内存
  *pi=10;     printf("*pi=%d\n",*pi);
  *pl=20;     printf("*pl=%d\n",*pl);
  *pd=10.5;   printf("*pd=%.1f\n",*pd);
  strcpy(pc,"西施"); printf("*pc=%s\n",pc);
  strcpy(pst->name,"杨玉环"); pst->age=21;
  printf("name=%s,age=%d\n",pst->name,pst->age);
  
  // 释放动态分配的内存
  free(pi); free(pl); free(pd); free(pc); free(pst);
}

running result

Here Insert Picture Description

Second, the memory is exhausted

When using dynamic memory allocation technology, distribution out of memory must be released in time, otherwise it will cause the system to run out of memory, which is saying is simple, it seems very easy to do, but in the actual development, programmers tend to be full of loopholes.

Memory problems are one of the major issues C programmers, beginners nightmare.

Third, the field guide

Wild pointer is invalid pointer, the null pointer different from the wild pointer can not be simply judged by whether NULL avoided, but only to try to reduce by develop good programming habits.

1, pointer variable uninitialized

Pointer variable when just been created will not necessarily become null pointer is automatically initialized (and compiler-related), it defaults to possible random, it will be chaos refers to stretch. So, while creating a pointer variable should be initialized, or the value of the pointer is set to 0, or to point to legitimate memory.

int *pi=0;

or

int i;
int *pi=&i;

2, after the release of the pointer is not blank

Pointer in memory when free will to relieve pointer, but the pointer will not necessarily be assigned
0 (also related to the compiler), illegal operation of the memory if the pointer after the release operation, the equivalent. Immediately after the release of the memory pointer is set to 0.

free(pi);
pi=0;

Fourth, the application experience

1, declare an array of improvements

In earlier standard C language, the arrays must be defined with a constant size is specified, the variables can not be used.

char str[101];        // 可以这样
int len=101;
char str[len];         // 不可以这样

Program at run time, if you want to define a string of characters to 100 characters, how to do that, only through the dynamic allocation of memory technology.

char *str=malloc(101);

Now, you can define an array with a variable size is specified, it is not necessary for memory dynamically allocated array.

There, C ++ is a string of variable length strings, very easy to use, programmers do not have to be concerned about memory problems.

2, the list

The list is a classic C language data structures, the equivalent of a dynamic array of structures, very clever, powerful, but the operation is also troublesome, here I not introduced.

In C ++, instead of finished container full list of features, extremely easy to use, programmers do not have to be concerned about memory problems.

3, my suggestion

In China, there is no pure C programmer, if he does not C ++, C dedication is not how much he has, probably not C ++.

At least ten years, I no longer use dynamic memory allocation technology, can not imagine what scenes have to use dynamic memory allocation technology.

Oh, embedded development may be an exception, there may be other C can not only be used in C ++ scene.

What technology on the dynamic memory allocation is not tall, I'm a practical programmer, not to their own digging, regardless of the level of this level.

Five, Homework

Write the sample program, this section describes the knowledge of all the demo again, the demo program can deepen your understanding and mapping.

Sixth, Copyright

C Language Technology Network original article, reproduced please indicate the source link to the article, the author and original.
Source: C Language Technology Network (www.freecplus.net)
Author: Ethics code Agriculture

If the article typos, or content errors, or other suggestions and comments, please correct me message, thank you very much! ! !

Published 29 original articles · won praise 2 · Views 674

Guess you like

Origin blog.csdn.net/m0_45133894/article/details/104649733