code gives segmentation fault(code dumped)

Viewed 30

I dont know why this code gives segementation fault(code dumped) is there something wrong with the syntax

#include <stdio.h>

int checksub(char strng){
  int a=strlen(strng);
  printf("%d",a);
}
int main(){
  checksub("twoi");
}
1 Answers

You're passing a char* argument, so you must accept one. Further, you're promising to return int but fail to do so. Third, you've got a single-use variable that's basically irrelevant, so you can simplify to this:

void checksub(char* strng) {
  printf("%d", strlen(strng));
}

Where strlen() returns size_t, you'll actually need:

void checksub(char* strng) {
  printf("%zu", strlen(strng));
}

--

There's a lot of things your compiler should have warned you about here, so turn on -Wall or equivalent and pay close attention.

Related