#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// fun1使用方式1创建n行m列动态二维整数数组
void fun1(int n, int m) {
int **array1 = (int **)malloc(n * sizeof(int *));
int i = 0;
int j = 0;
for (;i < n;i++) {
array1[i] = (int *)malloc(m * sizeof(int));
}
for (;i < n;i++) {
for (;j < m;j++) {
array1[i][j] = i * j;
}
}
for (i = 0;i < n;i++) {
free(array1[i]);
}
free(array1);
}
// fun2使用方式2创建n行m列动态二维整数数组
void fun2(int n, int m) {
int **array2 = (int **)malloc(n * sizeof(int *));
array2[0] = (int *)malloc(m * n * sizeof(int));
int i = 0;
for (i = 1;i < n;i++) {
array2[i] = array[0] + i * m;
}
free(array2[0]);
free(array2);
}
int main() {
fun1(10, 100); // fun2性能优于fun1
fun2(10, 100);
return 0;
}
方式和方式2的内存分配如下:
方式2内存分配是连续的,而且malloc和free次数更少,因此性能更高。
#编译
gcc -g -o Test test.c
#使用valgrind查内存泄漏
valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./Test