I am trying to create strlen
in C's standard library by myself like following, named it mystrlen
. I added other parts to make it run.
I used vim editor to write the code and gcc to run the code. The code had been successfully compiled.
#include <stdio.h>
int mystrlen(const char* str){
int i;
for (i=0;str[i]!='\n';i++);
return i;
}
int main(void){
char input[100];
gets(input);
printf("The length of your string : %d\n", mystrlen(input));
return 0;
}
Then, I tried to run .exe
file,
when I input the abc
, followings were displayed:
warning: this program uses gets(), which is unsafe.
abc
Segmentation fault: 11
I have also tested some other input strings and the result were the same.
When I input the aka
, Segmentation fault: 11
didn't appeared and shows the length as 104
.
warning: this program uses gets(), which is unsafe.
aka
The length of your string : 104
I have searched on the Internet about Segmentation fault: 11
, but I couldn't find any similar situation with me. There seems to be memory access problems when Segmentation fault: 11
occurs, but I'm not sure where memory access failed.
Question
Could you please tell me how to improve this code to work as same as the strlen
function in C's standard library?
Notation
During lots of trials by myself, I found strlen
in C's standard library is unsigned long
type, but I don't think this is the reason of Segmentation fault: 11
because no error regarding type
appeared.
References
I wrote my code referred this link.