C 动态内存分配

本文介绍了在 C 程序中使用动态分配内存相关的函数:malloc()、calloc()、free() 和 realloc()。

在 C 语言编程中,有几个和动态分配内存相关的函数:malloc()calloc()free()realloc()

如您所知,数组是固定数量值的集合。一旦声明了数组的大小,就不能更改它。

有时您声明的数组大小可能不够。要解决此问题,您可以在运行时手动分配内存。这在 C 语言编程中称为动态内存分配。

分配内存动态相关函数有:malloc()calloc()realloc()free(),他们定义在 <stdlib.h> 头文件中。

malloc()

malloc() 用来分配内存。

malloc() 函数分配指定字节数的内存块。它返回一个 void 指针, 该指针可以转换为任何形式的指针。

malloc() 的语法

ptr = (castType*) malloc(size);

例子

ptr = (float*) malloc(100 * sizeof(float));

上面的语句分配了 400 字节的内存。这是因为 float 的大小是 4 个字节。而且,指针 ptr 保存分配的内存中第一个字节的地址。

如果无法分配内存,则表达式会产生一个 NULL 指针。

C calloc()

malloc() 函数分配内存但并不初始内存,而 calloc() 函数分配连续的内存并将所有位初始化为零。

calloc() 的语法

ptr = (castType*)calloc(n, size);

例子:

ptr = (float*) calloc(25, sizeof(float));

上面的语句在内存中为 25 个 float 类型的元素分配了连续的空间。

C free()

使用 calloc()malloc() 动态分配的内存不会自动释放。我们必须显式使用 free() 来释放空间。

free() 的语法

free(ptr);

该语句释放 ptr 所指向的内存中分配的空间。

示例 1:malloc() 和 free()

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

int main() {
  int n, i, *ptr, sum = 0;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) malloc(n * sizeof(int));

  // if memory cannot be allocated
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);

  // deallocating the memory
  free(ptr);

  return 0;
}

输出

Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156

在这里,我们动态分配了内存 n int 大小的内存空间。

示例 2: calloc() 和 free()

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

int main() {
  int n, i, *ptr, sum = 0;
  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) calloc(n, sizeof(int));
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  free(ptr);
  return 0;
}

输出

Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156

C realloc()

如果动态分配的内存不足或超过要求,您可以使用该 realloc() 函数更改先前分配的内存大小。

realloc() 的语法

ptr = realloc(ptr, x);

这里, 指针 ptr 分配了新的内存大小 x

示例 3:realloc()

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

int main() {
  int *ptr, i , n1, n2;
  printf("Enter size: ");
  scanf("%d", &n1);

  ptr = (int*) malloc(n1 * sizeof(int));

  printf("Addresses of previously allocated memory:\n");
  for(i = 0; i < n1; ++i)
    printf("%pc\n",ptr + i);

  printf("\nEnter the new size: ");
  scanf("%d", &n2);

  // rellocating the memory
  ptr = realloc(ptr, n2 * sizeof(int));

  printf("Addresses of newly allocated memory:\n");
  for(i = 0; i < n2; ++i)
    printf("%pc\n", ptr + i);

  free(ptr);

  return 0;
}

输出

Enter size: 2
Addresses of previously allocated memory:
26855472
26855476
Enter the new size: 4
Addresses of newly allocated memory:
26855472
26855476
26855480
26855484