【问题标题】:free() 2D Arrays in C Using malloc使用 malloc 的 C 中的 free() 2D 数组
【发布时间】:2011-12-15 15:06:29
【问题描述】:

我想使用 free() 从内存中删除整个矩阵数组。我该怎么做?

分配数组:

// test.h
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define BYTE unsigned char
#define  my_array(n_height, n_width) (BYTE **)create_array(sizeof(BYTE), (n_height), (n_width))

char  **create_array(int u_size, int height, int width);
char  **create_array(int u_size, int height, int width)
{
    char  **array;
    int     i;

    if (!(array=(char **)malloc(height*sizeof(char *)))) {
        printf("Memory allocation error.\n");
        exit(0);
    }
    if (!(array[0]=(char *)malloc(height*width*u_size))) {
        printf("Memory allocation error.\n");
        exit(0);
    }
    for (i=1; i<height; i++)
        array[i] = array[i-1] + width*u_size;
    return array;
}

// test.c
#include "array.h"
int main()
{
    unsigned char *bytes;
    BYTE  **matrix;
    matrix = my_array(height, width);

    int c = 0;
    for (int h=0; h < height; h++) {
        for (int w=0; w < (width); w++) {
            matrix[h][w] = bytes[c];
            c++;
        }
    }

    printf("Done.\n");

    free(matrix); // really empty memory??
}

我不确定使用 free(matrix) 时矩阵是否已完全从内存中删除;

【问题讨论】:

    标签: c arrays matrix free


    【解决方案1】:

    每次调用malloc(),您必须调用free() 一次。你不能“愚弄”free() 进入 free:ing 几个块。如果您希望只调用一次free(),则需要确保在一次调用malloc() 时分配所有需要的内存。

    【讨论】:

      【解决方案2】:

      如果你喜欢,你可以使用漂亮的 C99 指向可变长度数组的指针。

      这样分配:

      char (*arr)[width] = emalloc(width*height);
      

      这样的索引:

      arr[23][10] = 2; //row 23, column 10
      

      像这样免费:

       free(arr);
      

      【讨论】:

      • @Dave:我会试试你的方法。谢谢!
      • @Alex emalloc() 是整个 Plan9 中用于返回有效指针或打印错误并退出的 malloc() 的名称。
      【解决方案3】:

      如果你想检查内存是否被释放,你应该使用Valgrind程序。
      The Valgrind Quick Start Guide

      在这种情况下,试试这个:

      free(matrix[0]);
      free(matrix);
      

      【讨论】:

      • 这正是我在发布问题之前使用的代码。我不确定,因为我得到了在线错误 -> free(matrix[i]); : test(830,0x7fff73cd4960) malloc: *** 对象 0x117439a4c 错误:未分配指针被释放 *** 在 malloc_error_break 中设置断点进行调试 (gdb)
      • 没错,你只分配了两次,所以你也必须释放两次。我推荐你使用 valgrind 程序,它是一个很棒的工具。
      • 感谢您的提示!我现在明白了: for(int i = 0; i
      【解决方案4】:

      你有两个mallocs,所以你需要两个frees。但是如果你重新安排你的分配,你可以优化一点:

      /...
      void* mcontent;
      if (!(mcontent = malloc(height*sizeof(char*) + height*width*u_size))) {
          printf("Memory allocation error.\n");
          exit(0);
      }
      array = (char **)mcontent;
      array[0]=(char *)(mcontent + height*sizeof(char*));
      

      这有两个好处。首先,可用性:您只需要释放您的矩阵“对象”,而不用担心它是如何制作的。第二,效率:你有局部性并且只有一个分配,这两者都意味着速度。

      【讨论】:

      • 谢谢!您的代码对我来说很清楚,可以理解如何使用 free() ,因为我之前一直在循环中挣扎以释放内存。我现在明白了。
      • 如果动态内存分配失败,您应该使用exit(EXIT_FAILURE);exit(1); 而不是exit(0);
      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 2015-04-23
      • 2021-01-18
      • 2011-06-06
      相关资源
      最近更新 更多