我是 C 编程新手。我需要一个 (10^5)*(10^5)
矩阵,在其中定义一个圆形边界。边界内的矩阵项将为 1,边界外的矩阵项将为 1 0.为了检查,我已经从 (1000*1000)
开始,如果我不使用 free(ar)
语句,它会打印整个矩阵。当我使用 (11*11)
矩阵并相应地更改圆形边界,并通过打印显示先前条目的第一行来检查 free(ar)
操作。我正在使用 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
会导致未定义的行为。因此,如果您不想在释放它后访问它,请在
NULL
(只是一个很好的做法)
free(ar);
ar=NULL;
这样,如果您尝试访问它,您的程序就会崩溃,这样您就知道发生了错误。
关于c - free() 无法释放我的 C 代码中动态分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624425/