A Buffer Overflow is caused by writing data over the border of reserved memory space for something.
Which could cause all kind of errors and unwanted behaviours.
With sprintf you can't control how much characters(bytes) are being written into a reserved memory space.
the last character is always a "\0" escape sequence with sprintf and snprintf. So for a string of 4 characters like "abcd" I would need to reserve 5 chars(bytes) with something like "char strBuffer[5]".
Example:
char strBuffer[5];
sprintf(strBuffer, "123456");
I reserve 5 bytes(chars) for the char buffer but try to write a string into it that's 6 bytes(chars)+1(for "\0") long. In other words I'm overflowing the the char buffer by 2 bytes(chars) which is being written into unknown memory area like described above.
With snprintf I can control how many characters(bytes) are written into the char buffer at max(which should be the number of reserved chars(bytes) for the char buffer) to avoid any overflow of data over the area of reserved memory.
Example:
char strBuffer[5];
sprintf(strBuffer, sizeof(strBuffer), "123456");
The expected result would be "1234" because the last and 5th character must be the "\0" escape sequence so it's actually "1234\0"
But u can't see the escape sequence, it's only for the program to know where the string ends.
I hope this helped everyone.
Here is an example:
https://onlinegdb.com/KB_da67uI