+ 1

Why my code print out more characters than its limit?

Here's my code: #include <stdio.h> /// The #include directive will call the header file called stdio.h. This Library have some standard input and output functions. int main() ///Entry point to the program. { char a[15]; ///An array that contains a space of 15 characters named a. printf("Enter a string\n"); ///Ask the user to enter some string (a sequence of letters). gets(a); ///A function used to gets a string from the user. Store that information in the 'a' array. printf("You just typed: "); puts(a); /// print out the letters of the 'a' array. return 0; ///End of program. } Note: I'm a beginner, so I might write something wrong... The char a[15] can hold 15 characters, but when I typed more than 15 characters, it still prints out.

20th Dec 2018, 6:55 AM
Konybud
Konybud - avatar
2 Answers
+ 1
The size of an array is constant, it is not resized. gets function does not check array bound and often invokes undefined behavior. Never use gets, instead you can use fgets as below : fgets(a, 15, stdin); For more Info read the following article : https://www.geeksforgeeks.org/fgets-gets-c-language/
20th Dec 2018, 7:19 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 6
"The char a[15] can hold 15 characters, but when I typed more than 15 characters, it still prints out." Any input string > 15 characters leads to buffer overflow. It must be big enough to handle any possible inputs like `char a[2000]` and also a mechanism to check the length of the input against the maximum buffer size.
20th Dec 2018, 7:24 AM
Babak
Babak - avatar