我分配了一个二维指针数组。我需要使用数组符号(例如索引或偏移值)来释放此指针数组。
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/