Im new to coding and C, and cant found an explenation to this can someone explain me please: Piece of my code Why does those two last random characters pop up if I enter 8, but if I input 6 it doesn´t. It is related to null characters or something? Please I need an explenation.
I tried almost everything, still figuring out, can´t found an explenation.
CodePudding user response:
In C, strings need to end with a special character called the NUL
termination character. The value of that character is 0
.
If you pass a string to printf (%s
), it expects the string to end with 0
.
Since you don't set the NUL
termination, the printf
function does not know when to stop reading characters from the string.
This is called a buffer over read: you're reading past your allocated buffer (aster
in that case).
Make sure to terminate aster
and it'll work.
One way of achieving this would be to change char aster[n];
to char aster[n 1];
(allocate one character more for the NUL
termination character) and then setting aster[n] = 0;
.
Consider n = 3
memory will look like this: (OUT OF BOUNDS means the memory afterwards doesn't belong to aster
and is something else, we don't know what it is).
aster[0] = ?
aster[1] = ?
aster[2] = ?
aster[3] = ? <OUT OF BOUNDS>
aster[4] = ? <OUT OF BOUNDS>
aster[5] = ? <OUT OF BOUNDS>
aster[6] = ... and so on
After your code memory will look like this:
aster[0] = *
aster[1] = *
aster[2] = *
aster[3] = ? <OUT OF BOUNDS>
aster[4] = ? <OUT OF BOUNDS>
aster[5] = ? <OUT OF BOUNDS>
aster[6] = ... and so on
printf will look at each character. It should stop at aster[3]
but it doesn't know that because there isn't a well-defined character at that place. This is why it might work sometimes, but other times it will not work. It's undefined behaviour.
Changing the code to always set the NUL
character it will look like this:
aster[0] = *
aster[1] = *
aster[2] = 0
aster[3] = ? <OUT OF BOUNDS>
aster[4] = ? <OUT OF BOUNDS>
aster[5] = ? <OUT OF BOUNDS>
aster[6] = ... and so on
In that case printf
will NEVER read past aster[2]
.
In any case, it's always a no-no to read or write past your memory buffers ;)
Also you need to intialize your loop variable i
to 0
.