我正在编写一个程序,从更大的矩阵中提取子矩阵块(源代码的一半(。
其思想是在行上循环,并使用memcpy从源矩阵中复制每一行。
唯一的问题是,当我对初始源矩阵进行free()
时,我会得到munmap_chunk()
错误。我知道当我释放一个malloc没有分配的指针时会发生这种情况。但这在这里毫无意义!我试图释放的mat[i]
是由malloc分配的。它只在memcpy中用作源。memcpy正在修改源吗?!
我的代码如下:
void print(int ** data, size_t m,size_t n)
{
int i,j;
printf("n");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{
printf("%d ",data[i][j]);
}
printf("n");
}
}
void init(int** tab, int n,int m ){
const int size_s = 8;
int mat[size_s][size_s] = {
{ 1, 2, 3, 4, 5, 6, 7, 8},
{ 9,10,11,12,13,14,15,16},
{17,18,19,20,21,22,23,24},
{25,26,27,28,29,30,31,32},
{33,34,35,36,37,38,39,40},
{41,42,43,44,45,46,47,48},
{49,50,51,52,53,54,55,56},
{57,58,59,60,61,62,63,64}
};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tab[i][j]= mat[i][j];
}
}
}
--主要功能
int main (void){
const int n = 8;
int sub_mtrx_size = n/2;
int ** mat = malloc(sizeof(int*) * n);
int ** submat = malloc(sizeof(int*) * n/2);
for (int k = 0; k < n; k++) {
mat[k] = malloc(sizeof(int) * n);
if ( k < n/2){
submat[k] = malloc(sizeof(int) * (n/2));
}
}
init (mat,n,n);
// start problem: when doing memcpy this issue happen, commenting this leads to no errors
memcpy( submat[0] , mat[0], sub_mtrx_size* sizeof(&submat) );
memcpy( submat[1] , mat[1], sub_mtrx_size* sizeof(&submat) );
memcpy( submat[2] , mat[2], sub_mtrx_size* sizeof(&submat) );
memcpy( submat[3] , mat[3], sub_mtrx_size* sizeof(&submat) );
// end problem
print(submat,4,4);
for (int i = 0; i < n; i++)
{
// free(mat[i]); // this line creates the problem !
if ( i < n/2){
free(submat[i]);
}
}
free (mat);
free (submat);
return 0;
}
如何避免此问题并正确释放内存?
感谢
调用类似的memcpy
memcpy( submat[0] , mat[0], sub_mtrx_size* sizeof(&submat) );
不正确。表达式CCD_ 4给出类型为CCD_。
你需要写
memcpy( submat[0] , mat[0], sub_mtrx_size* sizeof( int) );
或
memcpy( submat[0] , mat[0], sub_mtrx_size * sizeof( *submat[0] ) );