我对c程序有一些奇怪的问题。我在网上学习c语言编程,还练习了一些练习。其中之一是关于一种称为腐蚀的成像技术。假设有一幅图像,它有两种类型的像素,用‘’表示。或“#”。当一个像素被4个'#‘字符包围时,它会被保留,而在另一种情况下,它会被替换为’‘。性格。输入N表示应用腐蚀的次数,H和L表示图像的高度和宽度,以及由‘’组成的一个矩形字符。和“#”字符。对于实例输入:
1 //N
4 //H
4 //L
....
.###
####
####
and the output is
....
....
.##.
....问题是,在线编译器(测试一系列随机输入)拒绝我的代码,告诉我内存溢出
以下是代码
#include <stdlib.h>
#include <stdio.h>
//test wether a pixel is surrounded by 4 '#' characters
char test(int i, int j,int H, int L, char c[H][L]){
int k=0;
int l=0;
char result='-';
if((i==0)||(i==H-1)||(j==0)||(j==L-1)){
result='+';
}
else{
for(k=0;k<2;k++){
for(l=0;l<2;l++){
if(c[i+(1-2*k)*l][j+(1-2*k)*(1-l)] =='.'){
result='+';
break;
}
else{
}
}
if(result=='+'){break;}
else{}
}
}
return result;
}
//The erode function that replaces the image by one in which '#' characters are replaced by '.' characters when it is not surrounded by 4 '#' characters
char **erode(int H, int L, char c[H][L]){
int i;
int j;
char ch='-';
char **d = malloc (H * sizeof (int *));
for (i = 0; i < H; i++) {
d[i] = malloc (L * sizeof (int));
}
i=0;
for (i=0;i<H;i++)
{
for (j=0;j<L;j++)
{
ch=test(i,j,H,L,c);
if(ch=='+'){
d[i][j]='.';
}
else{
d[i][j]=c[i][j];
}
ch='-';
}
}
for (i= 0; i < H; i++) {
free(d[i]);
}
free(d);
return d;
}
//here are computed the inputs and outputs
int main()
{
int i=0;
int j=0;
int N;
int H;
int L;
char o;
scanf("%d",&N);
scanf("%d",&H);
scanf("%d",&L);
scanf("%c",&o);
char c[H][L];
char d[H];
char ero[H][L];
while (i<H)
{
while (j<L)
{
scanf("%c",&c[i][j]);
j++;
}
j=0;
scanf("%c",&d[i]);
i++;
}
int l;
int m;
int n;
for(l=0;l<N;l++){
for (i=0;i<H;i++)
{
for (j=0;j<L;j++)
{
ero[i][j]=erode(H,L,c)[i][j];
}
}
for (m=0;m<H;m++)
{
for (n=0;n<L;n++){
c[m][n]=ero[m][n];
}
}
}
for (i=0;i<H;i++)
{
for (j=0;j<L;j++){
printf("%c",c[i][j]);
}
printf("\n");
}
}(代码远不是最优的,因为我试图对其进行调试,并使某些东西真正分解)
有谁知道我为什么会有这个错误的消息吗?
发布于 2012-07-25 05:51:01
这可能是因为在erode函数中,您多次使用malloc,但从未调用过free。实际上,您可以在main的三重循环中调用erode。这表明它可能被调用了很多次,但是当分配的内存被释放时,完全有可能是内存耗尽了,这解释了错误消息。当您不再需要内存时,要更加小心地使用free释放内存。
https://stackoverflow.com/questions/11639807
复制相似问题