Andrei Stan
Andrei Stan

Reputation: 1

Segmentation fault - weird debugging with gdb

I'm working in C, Linux terminal. I need to find a pattern in a text and recolor it. GDB debugging can locate the function that is causing the problem via (gdb) backtrace, but it shows me a terrible message when I try to find the exact line:

Error

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)

The broken function is 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);
}

Upvotes: 0

Views: 573

Answers (2)

anuplohiya
anuplohiya

Reputation: 46

Updating diff to p-text in while loop where both pointer points to different array doesn't make sense. It is undefined behavior.

Also code has other issues.

  1. Uninitialized variable.
  2. Less optimized as number of call can be reduced.

Upvotes: 0

Employed Russian
Employed Russian

Reputation: 213375

it shows me a terrible message when I try to find the exact line:

There is nothing terrible, weird or unusual about this message, you just need to learn proper debugging technique.

What's happening is that the segmentation fault doesn't happen in your code, it happens inside GLIBC code (inside strstr), because you called strstr with bad arguments.

To find which call to strstr that was, use GDB up command to step out of GLIBC code, and into your code. Once you are inside find_and_recolor, you would be able to see the exact line, and print values of text, dif and pattern which caused your crash (assuming you compiled your code for debugging, i.e. with the -g flag).

Upvotes: 3

Related Questions