C语言 分段错误 - 使用 gdb 进行奇怪的调试



我在C,Linux终端工作。我需要在文本中找到一个图案并重新着色。GDB 调试可以通过 (gdb( 回溯找到导致问题的函数,但是当我尝试找到确切的行时,它向我显示一条可怕的消息:

错误

Program received signal SIGSEGV, Segmentation fault.
strstr_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strstr-sse2-unaligned.S:40
40 ../sysdeps/x86_64/multiarch/strstr-sse2-unaligned.S: No such file or dir
ectory.
(gbd)

损坏的函数find_and_recolor:

char* my_replace(char *text, char* replacement)
{
int lgreplacement = strlen(replacement);
int lgtext = strlen(text);
char *aux = (char*)malloc((lgreplacement + lgtext + 10) * sizeof(char));
strcpy(aux, replacement);
strcat(aux, text);
return(aux);
}
char* find_and_recolor(char* text, char* pattern)
{
int lgpattern = strlen(pattern);
int lgreplace = lgpattern + 10;//there are exactly 10 characters that must be inserted along the pattern word
int dif = 0;
char *p;
char *replacement = (char*)malloc(lgreplace * sizeof(char));
strcpy(replacement, "e[0;31m");
strcat(replacement, pattern);
strcat(replacement, "e[m");//to recolor a word in red, that word must be surrounded by those characters
while(p = strstr(text + dif, pattern))
{
p = my_replace(p, replacement);
p += lgreplace;
dif = p - text;
}
free(replacement);
return strdup(text);
}

当我试图找到确切的行时,它向我显示了一个可怕的消息:

此消息没有什么可怕的,奇怪的或不寻常的,您只需要学习正确的调试技术。

正在发生的事情是分段错误不会发生在您的代码中,而是发生在 GLIBC 代码中(strstr内部(,因为您使用错误的参数调用了strstr

若要查找要strstr的调用,请使用 GDBup命令跳出 GLIBC 代码并进入代码。一旦你进入find_and_recolor,你将能够看到导致崩溃的确切行,并打印textdifpattern的值(假设你编译了代码进行调试,即使用-g标志(。

将 diff 更新为 while 循环中的p-text个指针都指向不同的数组是没有意义的。这是未定义的行为。

代码还有其他问题。

  1. 未初始化的变量。
  2. 由于可以减少呼叫数量,因此优化较少。

最新更新