Could anyone help me to understand this strchr() C Segmentation fault?

1.5k views Asked by At

I'm diving into pointers and strings in C and I'm still getting used to some concepts. I tried to implement a version of the strchr() function – the same as in string.h – for study purposes, but something basic is still not right.

Here's my code:

#include <stdio.h>

char* my_strchr(const char* str, int c){
  if (str == NULL){
    printf("STR is NULL. Finishing the program\n");
    return NULL;
  }
  while (*str != '\0'){
    if (*str == c){
      return (char*) str;
    }
    str++;
  }
  return NULL;
}

int main(){
  char *a = "Hello World!";
  char *b;
  char c;

  printf("Type the character you want to find in the Hello World! string:\n");
  scanf(" %c", &c);

  b = my_strchr(a, c);

  printf("Character found! %c\n", *b);

  return 0;
}

I'm trying to figure out why this is returning a segmentation error. When I use gbd, it tells me that the error is in the last printf, which tries to print the *b.

Once my_strchr() returns a (char*) str, I'd have to store this return value in a char pointer variable, right?

2

There are 2 answers

1
Emil Laine On BEST ANSWER

When my_strchr doesn't find the character in the string, it returns NULL.

In this case b is NULL so *b is undefined behavior, which explains the segfault.

You might want to check the result of my_strchr before printing *b, e.g.:

if (b != NULL) {
  printf("Character found! %c\n", *b);
} else {
  printf("Not found...\n");
}
5
AudioBubble On

There are some logic issue like tuple_cat said.

But I also think you don't understand some concept, your code is not clean from my point of view.

I guess you just started coding in c so keep coding :)

First you return a char* in your function but you define argument of the function as

char* my_strchr(const char* str, int c)

In standard C you can't touch a constant you can't modify it that's the point of declaring a constant.

so change the function to

char* my_strchr(char* str, int c)

Then the correct way to return a char from a string is not

return (char*)str;

but just

return str;

At the end of your function.

This way you will send the address of the first char in char* (string). In a char* you do that by just giving the variable name.

I encourage you to read: https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html

RTFM !!! the char* part at 1.3.4 String Constants

Anyway good luck in your learning.