Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how does this code not cause a buffer overflow?

I have written the following code:

#include <stdio.h>


int main() {

    char s[10];

    while (fscanf(stdin, "%10s", s) != 1) {
    }

    printf("%s", s);
}

However the code runs perfectly fine.

How is this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The buffer s is size 10 but if i input a string such as helloworld which is 10 characters long the printf statement will print helloworld. How is this possible? I thought that it would print helloworl which i thought would look like this:

index 0: h
index 1: e
index 2: l
index 3: l
index 4: o
index 5: w
index 6: o
index 7: r
index 8: l
index 9: \0

why does this still work for me? and print helloworld? it seems like the null terminator is not even there. what is going on?

>Solution :

On this line: char s[10];
You asked for, and were allocated, 10 bytes in the array s.

All other data is beyond your control, and could have any value at all.
It could be used by device-drivers, or other programs, or even not be valid memory at all.

Then using fscanf you filled in 11 bytes with values HelloWorld and a \0 Terminator.

This is where the trouble starts. Your code filled in byte #11, which you have not explicitly reserved for your use.

printf will print a string until it finds a \0 terminator.
You do not have a guarantee of a terminator, so anything could happen.

Lucky for you, it seems that extra byte is available, and has not been overwritten by any other task/process/thread/device. There happens to be a \0 at the end of the text, and it behaves normally. But that is undefined behavior, and anything could very well have happened.

It would be totally legit if your computer had printed:

HelloWorldPrepareForGozerTheGozerian
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading