I don't understand this Error called "Buffer Overflow"

Vivek Tamang Source

I am learning C, it's my first programming language. I don't understand this Error called "Buffer Overflow". My code is as follows:

#include <stdio.h>
int main()
{
char a[5];
gets(a);
printf ("%s",a);
return 0;
}

Now when I type more that 5 words it should end with five, shouldn't it? But its showing some buffer error and I have no idea what to do about it. please help me with this. isn't that a[5] is the word limit of 5?

I'm very confused. Sorry if it distrub you all and thanks in advance.

c

Answers

answered 5 days ago Blaze #1

Actually, the limit is 4 characters, because a null terminator will be added to the end in order to form a valid string. This means that you need char a[6] if you want space for 5 characters.

Also, gets shouldn't be used for this exact reason. Instead, I would use scanf:

scanf("%5s", a);

This will tell it to read 5 characters at most, even if there are more.

With those changes, the program should look like this:

#include <stdio.h>
int main()
{
    char a[6];
    scanf("%5s", a);
    printf ("%s",a);
    return 0;
}

It's also possible to use fgets instead:

fgets(a, 5, stdin);

comments powered by Disqus