wow*_*ofe 3 c arrays free matrix
我想使用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;
}
Run Code Online (Sandbox Code Playgroud)
// 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??
}
Run Code Online (Sandbox Code Playgroud)
当我使用free(矩阵)时,我不确定矩阵是否已完全从内存中删除;
free()每次通话你必须拨打一次电话malloc().你不能"愚弄" free()自由:几个街区.如果您只想调用free()一次,则需要确保在一次调用中分配所有必需的内存malloc().