Noal99
Noal99

Reputation: 1

How I remediate buffer overrun problems like this?

I wanted to limit the number of characters the user enters for a char array name using fgets, but it still allows the user to enter more than the number of characters it is allowed to enter. How I correct this problem? Below is my snippet code:

char name[15];
printf("Enter your name: ");
getchar();
fgets(name);

Upvotes: -1

Views: 37

Answers (1)

0___________
0___________

Reputation: 67835

I wanted to limit the number of characters the user enters for a char array name using gets

You can't. Simply do not use this function. It depreciated and not safe. Use fgets instead. Also, check the return value to check if the function did not fail. Basically, you should always check for possible errors.

result = fgets(name, sizeof(name), stdin);
if(result) {/* do something */}
else  {/* error handling */}

Upvotes: 0

Related Questions