Why is it that the following:
#include <stdio.h>
int main(int argc, char *argv[])
{
char array[3] = {'1', '2', '3'};
printf("%s\n", array);
return 0;
}
produces 1238À§Wˇ
("123" + some random chars) as expected, while the same code with:
int main(void)
instead of argc
, argv
produces: 123
(despite there being no room for the null byte).
How is it that the lack of room for a null byte in array
with void
doesn't seem to matter?
When you do this:
char array[3] = {'1', '2', '3'};
printf("%s\n", array);
you are invoking undefined behavior, because the character array is not NUL terminated. You might get "123", or nothing at all, or somethink like that, or it might vary depending on any arbitrary conditions.
In your specific case, just an educated guess, after the local variable array
it is probably the memory for the function arguments, and those happen to be argc
and argv
. Depending on the actual arguments to main
and even the runtime values passed to the program, the bytes on thos memory positions will vary. And sometimes they will have to have a NUL byte at the proper place and affect the output of your program.
Anyway, my advice is not to overthink the cases of UB. They are best thought of as just undefined.