Segmentation fault (core dumped) error while passing string to bool function

Viewed 41

I keep getting this error when I try to pass these char values to bool function:

#include <stdio.h>
#include <stdbool.h> 
    
bool checksub(char *s1, char *v) {
  if (*s1==*v){
    return true;
  }
}
    
int main(void) {
  printf(checksub("a","a"));
}

Is that why I keep getting this error or is it a different reason?

segmentation fault (core dumped)
2 Answers

Your code has two problems. First of all, the checksub function has no return value in case the condition is false. The second problem is that in printf you are missing the format of the value you would like to print.

This is the working code:

#include <stdio.h>
#include <stdbool.h>


bool checksub(const char *s1, const char *v) {
  return (*s1 == *v);
}

int main(void) {
  printf("%d\n", checksub("a","a"));
}

I think that in C the best way to compare string is usign the strcmpstandard function. So, the checksub becomes:

bool checksub(const char *s1, const char *v) {
  return !strcmp(s1, v);
}
Related