c - C 中的内存释放

标签 c memory valgrind

我分配了一个二维指针数组。我需要使用数组符号(例如索引或偏移值)来释放此指针数组。

main.c

#include "practice.h"

int main() {
   int **A, **B, **C; // declare arrays.
   initNumSpace(A, B, C); // allocate space of arrays.
   freeNumSpace(A, B, C); // dealloc space of arrays.
}

练习.h

#ifndef PRACTICE
#define PRACTICE

/**
 * Function to alloc space of params.
 * @param A is a 2D pointer array.
 * @param B is a 2D pointer array.
 * @param C is a 2D pointer array.
*/
void initNumSpace();

/**
 * Function to free allocated space of params.
 * @param A is a 2D pointer array.
 * @param B is a 2D pointer array.
 * @param C is a 2D pointer array.
*/
void freeNumSpace();

#endif

练习.c

#include <stdlib.h>
#include "practice.h"

// allocate space of arrays.
void initNumSpace(int **A, int **B, int **C) {
    A = malloc(sizeof(int*) * 10);
    B = malloc(sizeof(int*) * 10);
    C = malloc(sizeof(int*) * 10);

    int** a = A;
    int** b = B;
    int** c = C;

    for (int i = 0; i < 10; i++) {
       *a = malloc(sizeof(int) * 10);
       *b = malloc(sizeof(int) * 10);
       *c = malloc(sizeof(int) * 10);

       a++;
       b++;
       c++;
   }
}

// de-alloc space
void freeNumSpace(int **A, int **B, int **C) {
   int** a = A;
   int** b = B;
   int** c = C;

   int* p = *a;
   int* q = *b;
   int* r = *c; 

   for (int i = 0; i < 10; i++) {
       p = *a;
       q = *b;
       r = *c;
           free(p);
           free(q);
           free(r);
       a++;
       b++;
       c++;
    }

    free(A);
    free(B);
    free(C);
}

Valgrind 中出现错误输出,指定滥用已分配或取消分配的空间。我想知道程序是否可以更好地释放空间而不滥用内存。

最佳答案

节省时间。启用所有警告

B = malloc(sizeof(int*) * 10);

Warning: assignment to 'int' from 'void *' makes integer from pointer without a cast [-Wint-conversion]

修复:

int** A、B、C; --> int **A、**B、**C;

分配给引用的对象,而不是类型

不易出错。更容易审查和维护。

// A = malloc(sizeof(int*) * 10);
A = malloc(sizeof *A * 10);

关于c - C 中的内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73803690/

相关文章:

C 中的 Char * 函数

c++ - C指针指向包含对齐的C结构的C++类的对齐问题

c - 兄弟子进程之间的管道份额

C 编译器错误 - 初始值设定项不是常量

c++ - Valgrind 对 FILE 的读取无效*

c - 使用 malloc 声明变量如何导致丢失位?

php - 经常提取大量行——我这里需要 memcached 吗?

c - 声明大数组时出现堆栈溢出异常

数组大小为零时的 C++ 内存分配行为

debugging - Valgrind 在 Fortran 代码中显示未初始化的变量