如何高效、可移植申请内存代码。

时间:2022-01-21 22:01:15


在视频编解码中,如何申请char   mem_2D[1920][1080],

char  mem_3D[4][1920][1080],

char mem_4D[6][4][1920][1080],高效 又  可移植申请内存呢?


请看如下代码:

看完后,如要申请的是 int  ,不是char ,如何修改? 如何要8字节对齐,如何修改?

请自己考虑,很简单的。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef unsigned char pel_t;
typedef int int_t;


int get_mem_2D(pel_t *** arr2D,int row,int column)
{
int i;
if ((*arr2D = (pel_t **)calloc(row,sizeof(pel_t*))) == NULL)
{
printf("can't calloc memory 2D\n");
return 0;
}
if (((*arr2D)[0] = (pel_t *)calloc(row * column,sizeof(pel_t))) == NULL)
{
printf("can't calloc memory 2D data\n");
return 0;
}
for(i = 1; i < row;i++)
(*arr2D)[i] = (*arr2D)[i- 1] + column;

return (row *column * sizeof(pel_t));
}


int get_mem_3D(pel_t ****arr3D,int frames,int row,int column)
{
int i;
if ( ( *arr3D = (pel_t ***) calloc(frames,sizeof(pel_t*)) ) == NULL)
{
printf("can't calloc memory 3D\n");
return 0;
}
for(i = 0 ;i < frames; i++)
get_mem_2D(&(*arr3D)[i],row,column);

return (frames * row * column * sizeof(pel_t));
}

int get_mem_4D(pel_t *****arr4D,int index,int frames,int row,int column)
{
int i;
if ( ( *arr4D = (pel_t ****) calloc(index,sizeof(pel_t*)) ) == NULL)
{
printf("can't calloc memory 3D\n");
return 0;
}
for(i = 0 ;i < index; i++)
get_mem_3D(&(*arr4D)[i],frames,row,column);

return (index * frames * row * column * sizeof(pel_t));

}



void free_2D(pel_t ** arr2D)
{
if (arr2D)
{
if (arr2D[0])
free(arr2D[0]);
else
printf(" free wrong");

free(arr2D);

}
else
{
printf( "not memory free\n");
}
}


void free_3D(pel_t *** arr3D,int frames)
{
int i;
if (arr3D)
{
for(i = 0; i < frames;i++)
{
free_2D(arr3D[i]);
}

free(arr3D);

}
else
{
printf( "not memory free\n");
}
}


void free_4D(pel_t **** arr4D,int index,int frames)
{
int i;
if (arr4D)
{
for(i = 0; i < index;i++)
{
free_3D(arr4D[i],frames);
}

free(arr4D);

}
else
{
printf( "not memory free\n");
}
}







void main(void)
{
int ret;
pel_t **arr;
pel_t ***arr3D;
pel_t ****arr4D;

ret = get_mem_2D(&arr,1080,1920);
printf("ret = %d\n",ret);


ret = get_mem_3D(&arr3D,4,1080,1920);
printf("ret = %d\n",ret);

ret = get_mem_4D(&arr4D,6, 4,1080,1920);
printf("ret = %d\n",ret);

free_2D(arr);
free_3D(arr3D,4);
free_4D(arr4D,6,4);


}