1

I have been trying to get a string input from a user using fgets but fgets does not wait for input so upon investagation I learned of the gets function which seems to be working fine. My questions are: 1. Why does gets work when I input more than 10 characters if I declared an array of only ten elements. Here is my code

#include<stdio.h>

int main(void){

    char name[10];

    printf("Please enter your name: ");
    gets(name);
    printf("\n");
    printf("%s", name);

    return 0;

}

my input when testing: morethantenletters
will output: 'morethantenletters'
Surely, this should have caused some errors, no? Since name is only ten elements long.

2. My next question is that my code also works when I use gets(&name) instead of gets(name)-- I do not understand why. The &name is sending the address of name.
while name is just sending the value of it, no?

3
  • 3
    Never use gets(). It provides no protection against memory overflow. Commented Jan 13, 2014 at 6:21
  • fgets does wait for input. Commented Jan 13, 2014 at 6:28
  • The blocking isn't the issue; both fgets() and gets() block appropriately for input. The trouble is gets() has no way to know how much space is available in the target char*. Commented Jan 13, 2014 at 6:31

2 Answers 2

2

That is exactly why you should always use fgets to replace gets. The array name has only 10 elements, but you are trying to store in it more than it's capable of. fgets prevents the program from buffer overflow, but gets doesn't.

It's undefined behavior when you are using gets in this way, don't use it.

Sign up to request clarification or add additional context in comments.

Comments

2
Since name is only ten elements long. 

Anything accepted more than 10 will be buffer overrun and may cause run time issues. So make sure your size is right. hint: Use getline or fgets instead.

while name is just sending the value of it, no?

For char arrays, name is also address to its starting position.

1 Comment

Use fgets() instead because the max size is specified. Don't use gets()!. The man pages clearly say this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.