我是c语言编程的新手,我需要一个(10^5)*(10^5)
矩阵,在其中定义一个圆形边界。边界内部的矩阵条目将为1且外部为0.为进行检查,我已从(1000*1000)
开始,并且在打印出整个矩阵时我不使用free(ar)
语句。当我使用(11*11)
矩阵并相应地更改圆形边界并通过打印第一行来检查free(ar)'s
动作时,它显示以前的条目。我使用的是Windows 64位计算机,和code :: blocks 13.12 IDE。这是我的(11 * 11)矩阵代码:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<conio.h>
#include<time.h>
#define NULL ((void *)0)
main()
{
int i,j,n,k,*ar;
float p;
printf("Enter n::::");
scanf("%d",&n);
ar=(int*)calloc((n*n),sizeof(int));
if(ar==NULL)
{
printf("Memory allocation error");
exit(1);
}
printf("\nThe matrix is::\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
p=((i-5)*(i-5)+(j-5)*(j-5));
if(p<16)
{
ar[i*n+j]=0;
printf("%d",ar[i*n+j]);
}
else
{
ar[i*n+j]=1;
printf("%d",ar[i*n+j]);
}
}
printf("\n");
}
printf("\nPRINTING COMPLETE\n");
free(ar-(n*n));
printf("\nThe first row of the matrix is\n\n");
for(k=0;k<11;k++)
{
printf("%d\t",*(ar+k));
}
}
输出为:
Enter n::::11
The matrix is::
11111111111
11111111111
11100000111
11000000011
11000000011
11000000011
11000000011
11000000011
11100000111
11111111111
11111111111
PRINTING COMPLETE
The first row of the matrix is
1 1 1 1 1 1 1 1
1 1 1
最佳答案
free(ar);
因此,在
ar
后访问free
会导致未定义的行为。因此,如果您不想在释放后访问它,则将其分配给NULL
(只是一个好习惯),然后 free(ar);
ar=NULL;
因此,如果您尝试访问它,您的程序将崩溃,从而使您知道已发生错误。
关于c - free()无法释放我的c代码中动态分配的内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31624425/