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

Time:09-23

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)

CodePudding user response:

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

CodePudding user response:

I believe it has to do with using printf with bools I am not sure who you compiled the program because it gave me errors with:

tmp.c:11:10: error: incompatible type for argument 1 of ‘printf’

which hints to the problem you should call printf with strings if you want to print bools use any of these methods here: What is the printf format specifier for bool? if you want more details about printf use https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

  •  Tags:  
  • c
  • Related