📜  使用malloc(),calloc(),free()和realloc()在C中进行动态内存分配

📅  最后修改于: 2021-05-25 20:58:30             🧑  作者: Mango

由于C是一种结构化语言,因此它具有一些固定的编程规则。其中之一包括更改数组的大小。数组是存储在连续内存位置中的项目的集合。
数组

可以看出,上述数组的长度(大小)为9。但是,如果需要更改此长度(大小),该怎么办。例如,

  • 如果存在只需要在此数组中输入5个元素的情况。在这种情况下,剩余的4个索引只是浪费了该数组中的内存。因此,需要将数组的长度(大小)从9减少到5。
  • 采取另一种情况。在这里,有9个元素组成的数组,所有9个索引均已填充。但是需要在此数组中再输入3个元素。在这种情况下,还需要3个索引。因此,阵列的长度(大小)需要从9更改为12。

此过程称为C中的动态内存分配

因此,C动态内存分配可以定义为在运行时更改数据结构(如数组)大小的过程。

C提供了一些功能来完成这些任务。 C在头文件下定义了4个库函数,以促进C编程中的动态内存分配。他们是:

  1. malloc()
  2. calloc()
  3. 自由()
  4. realloc()

让我们更详细地研究它们中的每一个。

  1. C malloc()方法

    C语言中的“ malloc”“内存分配”方法用于动态分配具有指定大小的单个大内存块。它返回类型为void的指针,该指针可以转换为任何形式的指针。它使用默认垃圾值初始化每个块。

    句法:

    ptr = (cast-type*) malloc(byte-size)

    例如:

    如果空间不足,分配将失败并返回NULL指针。

    例子:

    #include 
    #include 
      
    int main()
    {
      
        // This pointer will hold the
        // base address of the block created
        int* ptr;
        int n, i;
      
        // Get the number of elements for the array
        n = 5;
        printf("Enter number of elements: %d\n", n);
      
        // Dynamically allocate memory using malloc()
        ptr = (int*)malloc(n * sizeof(int));
      
        // Check if the memory has been successfully
        // allocated by malloc or not
        if (ptr == NULL) {
            printf("Memory not allocated.\n");
            exit(0);
        }
        else {
      
            // Memory has been successfully allocated
            printf("Memory successfully allocated using malloc.\n");
      
            // Get the elements of the array
            for (i = 0; i < n; ++i) {
                ptr[i] = i + 1;
            }
      
            // Print the elements of the array
            printf("The elements of the array are: ");
            for (i = 0; i < n; ++i) {
                printf("%d, ", ptr[i]);
            }
        }
      
        return 0;
    }
    
    输出:
    Enter number of elements: 5
    Memory successfully allocated using malloc.
    The elements of the array are: 1, 2, 3, 4, 5,
    
  2. C calloc()方法

    C语言中的“ calloc”“连续分配”方法用于动态分配指定类型的指定数量的内存块。它使用默认值“ 0”初始化每个块。

    句法:

    ptr = (cast-type*)calloc(n, element-size);

    例如:

    如果空间不足,分配将失败并返回NULL指针。

    例子:

    #include 
    #include 
      
    int main()
    {
      
        // This pointer will hold the
        // base address of the block created
        int* ptr;
        int n, i;
      
        // Get the number of elements for the array
        n = 5;
        printf("Enter number of elements: %d\n", n);
      
        // Dynamically allocate memory using calloc()
        ptr = (int*)calloc(n, sizeof(int));
      
        // Check if the memory has been successfully
        // allocated by calloc or not
        if (ptr == NULL) {
            printf("Memory not allocated.\n");
            exit(0);
        }
        else {
      
            // Memory has been successfully allocated
            printf("Memory successfully allocated using calloc.\n");
      
            // Get the elements of the array
            for (i = 0; i < n; ++i) {
                ptr[i] = i + 1;
            }
      
            // Print the elements of the array
            printf("The elements of the array are: ");
            for (i = 0; i < n; ++i) {
                printf("%d, ", ptr[i]);
            }
        }
      
        return 0;
    }
    
    输出:
    Enter number of elements: 5
    Memory successfully allocated using calloc.
    The elements of the array are: 1, 2, 3, 4, 5,
    
  3. C free()方法

    C语言中的“免费”方法用于动态取消分配内存。使用函数malloc()和calloc()分配的内存不会自行取消分配。因此,每当发生动态内存分配时,都会使用free()方法。它通过释放内存来帮助减少内存浪费。

    句法:

    free(ptr);

    例子:

    #include 
    #include 
      
    int main()
    {
      
        // This pointer will hold the
        // base address of the block created
        int *ptr, *ptr1;
        int n, i;
      
        // Get the number of elements for the array
        n = 5;
        printf("Enter number of elements: %d\n", n);
      
        // Dynamically allocate memory using malloc()
        ptr = (int*)malloc(n * sizeof(int));
      
        // Dynamically allocate memory using calloc()
        ptr1 = (int*)calloc(n, sizeof(int));
      
        // Check if the memory has been successfully
        // allocated by malloc or not
        if (ptr == NULL || ptr1 == NULL) {
            printf("Memory not allocated.\n");
            exit(0);
        }
        else {
      
            // Memory has been successfully allocated
            printf("Memory successfully allocated using malloc.\n");
      
            // Free the memory
            free(ptr);
            printf("Malloc Memory successfully freed.\n");
      
            // Memory has been successfully allocated
            printf("\nMemory successfully allocated using calloc.\n");
      
            // Free the memory
            free(ptr1);
            printf("Calloc Memory successfully freed.\n");
        }
      
        return 0;
    }
    
    输出:
    Enter number of elements: 5
    Memory successfully allocated using malloc.
    Malloc Memory successfully freed.
    
    Memory successfully allocated using calloc.
    Calloc Memory successfully freed.
    
  4. C realloc()方法

    C语言中的“重新分配”“重新分配”方法用于动态更改先前分配的内存的内存分配。换句话说,如果先前借助malloc或calloc分配的内存不足,则可以使用realloc动态地重新分配memory 。内存的重新分配将保持已经存在的值,并且将使用默认垃圾值来初始化新块。

    句法:

    ptr = realloc(ptr, newSize);
    
    where ptr is reallocated with new size 'newSize'.
    

    如果空间不足,分配将失败并返回NULL指针。

    例子:

    #include 
    #include 
      
    int main()
    {
      
        // This pointer will hold the
        // base address of the block created
        int* ptr;
        int n, i;
      
        // Get the number of elements for the array
        n = 5;
        printf("Enter number of elements: %d\n", n);
      
        // Dynamically allocate memory using calloc()
        ptr = (int*)calloc(n, sizeof(int));
      
        // Check if the memory has been successfully
        // allocated by malloc or not
        if (ptr == NULL) {
            printf("Memory not allocated.\n");
            exit(0);
        }
        else {
      
            // Memory has been successfully allocated
            printf("Memory successfully allocated using calloc.\n");
      
            // Get the elements of the array
            for (i = 0; i < n; ++i) {
                ptr[i] = i + 1;
            }
      
            // Print the elements of the array
            printf("The elements of the array are: ");
            for (i = 0; i < n; ++i) {
                printf("%d, ", ptr[i]);
            }
      
            // Get the new size for the array
            n = 10;
            printf("\n\nEnter the new size of the array: %d\n", n);
      
            // Dynamically re-allocate memory using realloc()
            ptr = realloc(ptr, n * sizeof(int));
      
            // Memory has been successfully allocated
            printf("Memory successfully re-allocated using realloc.\n");
      
            // Get the new elements of the array
            for (i = 5; i < n; ++i) {
                ptr[i] = i + 1;
            }
      
            // Print the elements of the array
            printf("The elements of the array are: ");
            for (i = 0; i < n; ++i) {
                printf("%d, ", ptr[i]);
            }
      
            free(ptr);
        }
      
        return 0;
    }
    
    输出:
    Enter number of elements: 5
    Memory successfully allocated using calloc.
    The elements of the array are: 1, 2, 3, 4, 5, 
    
    Enter the new size of the array: 10
    Memory successfully re-allocated using realloc.
    The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。