0

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?

  • 1
    `&x` may not be a string, because it may not be nil-terminated. You have undefined behaviour here. It might be predictable, it also might not. – Cheatah Nov 17 '22 at 09:19
  • 1
    Others have pointed out one problem, but a latent problem is that `%zu` is the correct printf formatting code for values of type `size_t` (as returned here by `strlen`). `%ld` will work if a `long` and `size_t` are the same size, and the value fits in a long, but that's not guaranteed. – Paul Hankin Nov 17 '22 at 09:27
  • I disagree with the closing. That link does not answer the question at all. –  Nov 17 '22 at 10:36

3 Answers3

1

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.

0

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.

Codo
  • 75,595
  • 17
  • 168
  • 206
-1

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • -1 for "it's not possible to reason" - we all know what the compiler is likely to do (especially with optimizations off) and the asker's results suggest that the compiler is in fact doing that likely thing. It's only impossible to reason if, for some reason, you pretend to not know anything apart from what's written in the C++ specification! – user253751 Nov 17 '22 at 09:52