简体   繁体   English

程序 C 错误 valgrind 分段错误

[英]Program C error valgrind segmentation fault

I compiled this C program and generated the executable but starting it gives me segmentation error.我编译了这个 C 程序并生成了可执行文件,但启动它给了我分段错误。 I debugged with valgrind and it gives me error on this line of strcpy code (ctfilename, app_data.ct_path) where app_data is a typedef struct of extern.h and ct_path is its variable.我用 valgrind 进行了调试,它在这行 strcpy 代码(ctfilename,app_data.ct_path)上给了我错误,其中 app_data 是 extern.h 的 typedef 结构,而 ct_path 是它的变量。 Valgrind's error is this: Valgrind 的错误是这样的:

== 27435 == Invalid read of size 1
== 27435 == at 0x4840094: strcpy (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
== 27435 == by 0x11CD49: GetColors (color.c: 304)
== 27435 == by 0x10C0F7: main (main.c: 162)
== 27435 == Address 0x0 is not stack'd, malloc'd or (recently) free'd

Anyone know how I can get it?有谁知道我怎么能得到它?

I attach the link with the sources on my google drive https://drive.google.com/file/d/10o66Xu20Maw_aD9Sc7yXWKRsJqeUhApQ/view?usp=sharing我附上我的谷歌驱动器https://drive.google.com/file/d/10o66Xu20Maw_aD9Sc7yXWKRsJqeUhApQ/view?usp=sharing上的源链接

First.第一的。 Do NOT use strcpy .不要使用strcpy Use a function which you can pass size as an argument, it can cause memory-safety problems like stack-based buffer overflows or heap-based buffer overflows.使用可以将大小作为参数传递的 function,它可能会导致内存安全问题,例如基于堆栈的缓冲区溢出或基于堆的缓冲区溢出。

strcpy is just "valid" when statically-defined strings are used as source data.当静态定义的字符串用作源数据时, strcpy只是“有效的”。

But anyway it is not a good practice.但无论如何,这不是一个好习惯。

And about the specific problem you are facing on valgrind:关于您在 valgrind 上面临的具体问题:

typedef struct {
    char * seq_directory;
    char  * sequence_name;
    char * colortable;
    char * fltctable;
    char * difftable;
    char * bitmap_path;
    char  * ct_path;
    char * pbm_path;
    XColor lforeground;
    XColor cursorcolor;
} AppData, *AppDataPtr;

Your AppData struct, defined as a global with name app_data in globals.c .您的AppData结构,在globals.c中定义为名为app_data的全局变量。

line of code where the SIGSEGV is triggered: strcpy (ctfilename, app_data.ct_path);触发 SIGSEGV 的代码行: strcpy (ctfilename, app_data.ct_path);

It appears that app_data.ct_path is NULL for some reason, and couldn't be accessed.由于某种原因, app_data.ct_path似乎是 NULL,无法访问。

$ grep -r 'app_data.ct_path'
color.c:    strcpy (ctfilename, app_data.ct_path);

And the only time app_data.ct_path is present is when you are trying to copy it's content to your stack buffer.并且app_data.ct_path唯一存在的时间是当您尝试将其内容复制到堆栈缓冲区时。

Why didn't you assign dynamic memory to the pointer?为什么不将动态 memory 分配给指针?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM