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?
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");
}