I am new to C and recently encountered this problem.
I have two pieces of code:
#include <stdio.h>
#include <string.h>
int main()
{
char x = 'a';
// char *y=&x;
printf("%ld\n", strlen(&x)); // output: 1
return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
char x = 'a';
char *y=&x;
printf("%ld\n", strlen(&x)); //output: 7
return 0;
}
What exactly happened when I added the variable y that it changed the result?
The code triggers undefined behavior.
It's not possible to reason about it very well, since whatever happens happens. It's probably going to treat the single-character variable as a string, and read the next byte to look for the terminator.
Since that byte is not, in fact, in a valid variable, the behavior is undefined and anything could happen. Don't do this.