C 内存管理

预计时间: 4分钟

内存管理

本章介绍 C 中的动态内存管理。 C 编程语言提供了多种内存分配和管理功能。 这些函数可以在<stdlib.h>头文件中找到。

  • void *calloc(int num, int size);
  • 分配一个num个元素的数组,每个元素的字节大小都是size

  • void free(void *address);
  • 释放由地址指定的一块内存块。

  • void *malloc(size_t size);
  • 分配一个num字节数组并保持它们未初始化。

  • void *realloc(void *address, int newsize);
  • 重新分配内存,将其扩展到newsize

动态分配内存

在编程时,如果您知道数组的大小,那么很容易,您可以将其定义为数组。例如,要存储任何人的姓名,最多可以包含 100 个字符,因此您可以定义如下内容 -

char name[100];

但是现在让我们考虑一种您不知道需要存储的文本长度的情况,例如,您想存储有关某个主题的详细描述。在这里,我们需要定义一个指向字符的指针,而不定义需要多少内存,然后根据需要,我们可以分配内存,如下例所示 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

   char name[100];
   char *description;

   strcpy(name, "Zara Ali");

   /* allocate memory dynamically */
   description = malloc( 200 * sizeof(char) );
	
   if( description == NULL ) {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   } else {
      strcpy( description, "Zara ali a DPS student in class 10th");
   }
   
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
}

当上面的代码编译并执行时,它会产生以下结果。

Name = Zara Ali
Description: Zara ali a DPS student in class 10th

可以使用calloc() 编写相同的程序;唯一的事情是你需要用 calloc 替换 malloc 如下 -

calloc(200, sizeof(char));

所以你有完全的控制权,你可以在分配内存时传递任何大小值,这与数组不同,一旦定义了大小,就无法更改它。

调整大小和释放内存

当您的程序出现时,操作系统会自动释放您的程序分配的所有内存,但作为一个好习惯,当您不再需要内存时,您应该通过调用函数free()释放该内存。

或者,您可以通过调用函数realloc()来增加或减少分配的内存块的大小。让我们再次检查上述程序并使用 realloc() 和 free() 函数 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

   char name[100];
   char *description;

   strcpy(name, "Zara Ali");

   /* allocate memory dynamically */
   description = malloc( 30 * sizeof(char) );
	
   if( description == NULL ) {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   } else {
      strcpy( description, "Zara ali a DPS student.");
   }
	
   /* suppose you want to store bigger description */
   description = realloc( description, 100 * sizeof(char) );
	
   if( description == NULL ) {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   } else {
      strcat( description, "She is in class 10th");
   }
   
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );

   /* release memory using free() function */
   free(description);
}

当上面的代码编译并执行时,它会产生以下结果。

Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th

您可以尝试上面的示例而无需重新分配额外的内存,并且 strcat() 函数会由于描述中缺少可用内存而出错。

更新于2022年04月14日