I'm studying C and in particular pointers and memory access. I wrote this simple program to count the number of chars in a string, but the "problem" is that it works when it should give me error.
More Specifically, even if I enter more characters than what is expected (5) the function mylen
is still able to correctly count the number of characters. I tried also with very large numbers (>50). Why?
#include <stdio.h>
int mylen(char*);
int main(){
char mystring[5];
printf("Enter a string: ");
scanf("%s", &mystring);
int lenght = mylen(mystring);
printf("The string is %d chars long", lenght);
return 0;
}
int mylen (char *ptr) {
int len;
len = 0;
char t;
while (*ptr != '\0'){
ptr++;
len ++;
}
return len;
}
P.S. I'm aware there are more efficient and secure ways to read a string, like getline()
, but I'm curious about this specific issue. Thanks for any clarification.