为什么我必须在使用它后解除分配指针?(ANSI-C)

Hie*_*yen 2 c pointers ansi

我读到这个:http://www.drpaulcarter.com/cs/common-c-errors.php#2.8 并且有一段代码:

#include <string.h>
#include <stdlib.h>
int main()
{
  char *st = malloc(20);   /* st points to allocated array*/

  strcpy(st, "abc");  /* st points to char array */
  free(st);                /* don't forget to deallocate when done! */
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ett 5

在大多数理智的操作系统上,你不必在退出时进行清理 - 这只是一个好习惯.

代码只是分配和释放内存的简单示例,在实际程序中,您将跟踪在程序运行时需要释放的内存,否则您将耗尽内存(或更可能的地址空间)

  • 如果您的代码将用于持续运行的服务,则必须始终小心清理.否则,你的内存不足.如果您只关心"退出时"清理,那么您可能不需要担心它. (3认同)