Why strlen() in C produces different output, but I have not been changing the argument?

99 Views Asked by At

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?

3

There are 3 best solutions below

1
unwind On

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.

0
Codo On

strlen() expects as string as its parameters. String in C are a sequence of chars terminated with a null char.

Your variable x is just a character without terminating null char. It is not a valid argument for strlen(). As such, the behavior is dangerous and undefined.

0
AudioBubble On

As said by others, you may not use strlen on a single character, as there is no guarantee of a null terminator.

In the first case, you were lucky that the 'a' was followed by a null byte in the mapping of the stack.

In the second case, possibly due to the definition of the variable y, the 'a' was followed by six nonzero bytes then a null.

Note that this is just a supposition. The behaviors could be different for a debug or a relase build. Such erratic phenomena are typical of undesirable memory accesses.