I have this simple program which works correctly.
#include<stdio.h>
int main(int argc, char *argv[]) {
int mystrlen(char *s);
char s[6] = "ABCDEF";
printf("%d", mystrlen(s)); // print 6
}
int mystrlen(char *s) {
char *p=s; /*Assigning the starting value to p */
while(*s != '\0') {
s = s + 1;
}
return s-p;
}
The only change which I will make is instead of int main(int argc, char *argv[])
, I will use int main(void)
, which I am not sending any command line arguments.
Now, the same program completely misbehaves for me!
#include<stdio.h>
int main(void)
{
int mystrlen(char *s);
char s[6]="ABCDEF";
printf("%d",mystrlen(s)); // prints 8 !!
}
int mystrlen(char *s) {
char *p=s; /*Assigning the starting value to p */
while(*s != '\0') {
s = s + 1;
}
return s-p;
}
Can anyone explain why this is the case? It was the last thing I expected to be wrong in the program. Is this compiler dependent behavior? FWIW, I am using gcc