[英]Why does this program crash when freeing?
当我使用这一行并试图释放指针时,我试图理解为什么这个程序会崩溃:
t_mat *C=malloc(sizeof(t_mat));
但适用于以下行(没有 memory 泄漏,没有崩溃,值 53 是我通过反复试验找到的最小值):
t_mat *C=malloc(sizeof(t_mat)+53);
程序:(while(1) 循环用于 memory 泄漏测试,不影响崩溃)
#include <stdio.h>
#include <stdlib.h>
typedef int t_mat[3][3];
t_mat* matice(t_mat A, t_mat B, char op)
{
t_mat *C=malloc(sizeof(t_mat)+53);
switch(op)
{
case '+':
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
*C[i][j]=A[i][j]+B[i][j];
return *C;
break;
case '-':
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
*C[i][j]=A[i][j]-B[i][j];
return *C;
break;
default:
free(C);
printf("Chyba\n");
return NULL;
break;
}
}
int main()
{
char op;
scanf("%c",&op);
getchar();
t_mat A = {0,1,2,3,4,5,6,7,8},B= {0,1,2,3,4,5,6,7,8},*C;
while(1)
{
C=matice(A, B, op);
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
printf("%d\n",*C[i][j]);
free(C);
C=NULL;
}
return 0;
}
我在这里错过了什么吗?
一元*
的优先级低于[]
。 你需要写(*C)[i][j]
。
像这样的陈述
*C[i][j]=A[i][j]+B[i][j];
和
printf("%d\n",*C[i][j]);
调用未定义的行为。 由于这个声明,变量C
的类型是int ( * )[3][3]
t_mat *C=malloc(sizeof(t_mat)+53);
所以首先你应该应用解引用运算符,然后才应用下标运算符
( *C )[i][j]=A[i][j]+B[i][j];
或者
printf("%d\n", ( *C )[i][j]);
否则程序有未定义的行为。
所以在 memory 分配中使用幻数53
没有任何意义。 写吧
t_mat *C=malloc(sizeof(t_mat));
这是一个演示程序。
#include <stdio.h>
#include <stdlib.h>
#define N 3
typedef int t_mat[N][N];
int main(void)
{
t_mat A =
{
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
t_mat B =
{
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
t_mat *C = malloc( sizeof( t_mat ) );
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
( *C )[i][j] = A[i][j] + B[i][j];
}
}
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%2d ", ( *C )[i][j] );
}
putchar( '\n' );
}
putchar( '\n' );
free( C );
return 0;
}
程序 output 是
0 2 4
6 8 10
12 14 16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.