But how this line while (*z++ = *x++);
can act as boolean 1/0
This is because in C, an assignment is an expression and it evaluates to the value that is assigned. When *x
reaches the final '\0'
terminator, it evaluates to 0
, therefore false
in a boolean context.
This is btw a nice source of bugs due to mistyping:
if (x = 1) // always true, as a side effect assigns 1 to x
And why I even set the malloc(0);
to zero it also works well without any problem??
Using the return value of malloc(0)
to write values is just undefined and "works by accident". You request zero bytes, so you are never allowed to write to this allocation and malloc()
could even return you a null pointer.
Citing myself here about undefined behavior:
Undefined behavior in C
C is a very low-level language and one consequence of that is the following:
Nothing will ever stop you from doing something completely wrong.
Many languages, especially those for some managed environment like Java
or C#
actually stop you when you do things that are not allowed, say,
access an array element that does not exist. C
doesn't. As long as your
program is syntactically correct, the compiler won't complain. If you do
something forbidden in your program, C
just calls the behavior of your
program undefined. This formally allows anything to happen when running
the program. Often, the result will be a crash or just output of "garbage"
values, as seen above. But if you're really unlucky, your program will seem
to work just fine until it gets some slightly different input, and by that
time, you will have a really hard time to spot where exactly your program is
undefined. Therefore avoid undefined behavior by all means!.
On a side note, undefined behavior can also cause security holes. This
has happened a lot in practice.