Home > database >  What am I doing wrong to get segmentation fault?
What am I doing wrong to get segmentation fault?

Time:03-25

I'm trying to replicate the function strstr. When my function finds to_find in str it works accordingly. If to_find is not in str I get segmentation fault, even though I created a condition to return NULL; if my str gets to '\o' without getting any matches.

This is my code:

#include <stdio.h>

char    *ft_strstr(char *str, char *to_find)
{
    char    *to_find_copy;
    char    *str_copy;

    to_find_copy = to_find;
    str_copy = str;
    while (*to_find_copy != '\0' || *str_copy != '\0')
    {
        if (*to_find_copy == *str_copy)
        {
            to_find_copy  ;
            str_copy  ;
        }
        else
        {
            to_find_copy = to_find;
            str  ;
            str_copy  ;
        }
    }
    if (*str_copy == '\0')
        return NULL;
    return (str);
}


int main(void)
{
    char str[50] = "Yesterday I went to the store";
    char to_find[50] = "Z";
    char *ptr;

    printf("\nString 1:   %s\nString 2:   %s\n", str, to_find);

    ptr = ft_strstr(str, to_find);
    
    printf("\nEncontrou:    %s\n", ptr);

    return 0;
}

Output:

String 1:   Yesterday I went to the store 
String 2:   Zer
zsh: segmentation fault  ./a.out

It should return NULL. I believe I must be overwriting the memory of an array but I don't understand why.

PS. I can only use 25 line in the function at max.

CodePudding user response:

You could try this code. Your code didn't give segmentation fault on my system, but it doesn't give correct results. It always returns NULL

I will return String "NULL" instead of NULL...

#include <stdio.h>

char *ft_strstr(char *str, char *to_find) {

  int found = 0;
  char *return_value = str;

  while (found == 0) {
    if (*to_find == *str) {
      to_find  ;
      str  ;
    } else {
      str  ;
      return_value  ;
    }
    if (*to_find == '\0') {
      found = 1;
      return return_value;
    }

    if (*str == '\0') {
      return "NULL";
    }
  }
}


int main(void) {
  char str[50] = "Yesterday I went to the store";
  char to_find[50] = "Zer";
  char to_find_2[50] = "ent";
  char *ptr;

  printf("\nString 1:   %s\nString 2:   %s\n", str, to_find);
  ptr = ft_strstr(str, to_find);
  printf("\nFound:    %s\n\n", ptr);
  printf("\nString 1:   %s\nString 2:   %s\n", str, to_find_2);
  ptr = ft_strstr(str, to_find_2);
  printf("\nFound:    %s\n", ptr);
  return 0;
}

OUTPUT:

> ./strstr

String 1:   Yesterday I went to the store
String 2:   Zer

Found:    NULL


String 1:   Yesterday I went to the store
String 2:   ent

Found:    ent to the store
  •  Tags:  
  • c
  • Related