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.
Could you please tell me how to improve this code to work as same as the strlen
function in C's standard library?
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.
CodePudding user response:
If you want to reimplement strlen
you should return a size_t
instead of an int
and check for str[i] != '\0'
instead of str[i] != '\n'
Pay attention to the warnings:
warning: this program uses gets(), which is unsafe.
gets
is no longer part of the standard and it was unsafe because there is no way to prevent buffer overflows with it. Anyway, gets
doesn't include the newline (that's why it segfaults reading beyond the limits of the array).
You must avoid this function and use fgets
(or getline
if available):
if (fgets(input, sizeof input, stdin))
{
input[strcspn(input, "\n")] = '\0'; // Strip the trailing newline
printf("The length of your string : %zu\n", mystrlen(input));
}
CodePudding user response:
Your problem is the check on the new line character str[i] != '\n'
. In C the NULL Terminator \0
determine the end of a string.
int mystrlen(const char* str){
int i;
for (i=0; str[i] != '\0'; i );
return i;
}