我不明白为什么我的代码会使堆栈粉碎

时间:2014-09-08 08:47:36

标签: c return-value variable-assignment

我的代码中有这个功能:

unsigned char **load_image(char *file_name)
{
    FILE *file;
    char ret[5],ret1[5],ret2[5],ret3[5],ret4[5];
    int height,width,max;
    int i,j,pom;
    unsigned char **loaded;

    file=fopen(file_name,"r");

   if( file == NULL )
       printf("didnt open \n");
   else 
       printf("opened! \n");

    fscanf(file,"%s %s %s %s %s",ret,ret1,ret2,ret3,ret4);
    fscanf(file,"%d",&width);
    fscanf(file,"%d",&height);
    fscanf(file,"%d",&max);

    loaded=alloc_uchar_array(height,width);

    for(i=0;i<height;i++)
        for(j=0;j<width;j++)
        {
            fscanf(file,"%u",&pom);
            loaded[i][j]=(unsigned char)pom;
        }

    fclose(file);

    return loaded;
}

我从主要方式称呼它:

int main(int a)
{
    unsigned char **test_source;
    unsigned char **test_target;
    unsigned char pom_print;
    intensity_function *intensity_f;
    intensity_function *transformation;
    int height=1024;
    int width=1024;

    test_source=load_image("silma_05_442_1.pgm");
    test_target=load_image("silma_06_450_1.pgm");

    print_image(test_source,height,width,"priklad1_source.pgm");
    print_image(test_target,height,width,"priklad1_target.pgm");

    intensity_f=finite_volume_method(test_source,test_target,height,width);

    return 0;    
}

如果我编译这段代码并进行调试,我会得到这个:

Starting program: /home/h1657/Work/bakalarka/a.out 
opened! 
*** stack smashing detected ***: /home/h1657/Work/bakalarka/a.out terminated

Program received signal SIGABRT, Aborted.
0x00007ffff7744bb9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56  ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) backtrace
#0  0x00007ffff7744bb9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1  0x00007ffff7747fc8 in __GI_abort () at abort.c:89
#2  0x00007ffff7781e14 in __libc_message (do_abort=do_abort@entry=1, fmt=fmt@entry=0x7ffff788e06b "*** %s ***: %s terminated\n") at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007ffff78197dc in __GI___fortify_fail (msg=<optimized out>, msg@entry=0x7ffff788e053 "stack smashing detected") at fortify_fail.c:37
#4  0x00007ffff7819780 in __stack_chk_fail () at stack_chk_fail.c:28
#5  0x0000000000407c9b in load_image (file_name=0x4089b2 "silma_05_442_1.pgm") at levelsetMethod.c:1380

我真的不明白是什么导致了这个问题。在main中将返回值返回或赋值给变量可能存在一些问题。

任何人都知道我做错了什么?

修改
这是我的pgm文件的求助:

P2
# Created by IrfanView
1024 1024
255
19 20 20 21 21 20 19 22 20 24 21 22 22 22 21 23 24 

......等等。里面没有其他的内容。我刚刚在返回加载变量之前调试了图像打印,它运行正常。第1380行是函数load_image的最后一行,它只包含}

1 个答案:

答案 0 :(得分:2)

pgm文件规范(http://netpbm.sourceforge.net/doc/pgm.html)似乎只表示文件头中的以下字符串:

  1. 幻数;
  2. 宽度;
  3. 高度;
  4. 最大灰度值。
  5. 文件的其余部分是二进制文件。第五次扫描到ret4将尝试写入ret [4],除非文件早期有一个黑色像素(因为黑色的0字节将被解释为字符串终结符)。

    还有两个评论:

    • 为字符串保留的内存不足以容纳大图像 (宽度为10000你需要一个ret1 [6]:5个字节 1,0,0,0,0和结束'\ 0')。

    • 解析不完整:Jongware正确指出了这一点 pgm文件可能包含注释(用井号标记)。