In: Computer Science
4.
Assignment Instructions:
Please respond with at least 100 words. Your initial post should address each of the topic below thoughtfully.
Topic: What are some ways to prevent out of bounds errors when reading input into C-strings?
To answer this question first let us understand the key terms.
i) C-String: It is an array of string. They are usually terminated by null character '\0'.
Advantage of C-String:
Execution of C-string statement are faster when compared to String data type (used in other language other than c and C++)
Disadvantage:
Size is fixed at compile time itself.
No functions to track the size of the c-string array
Possibility of error:
Situation1: while using built-in function
strcmp(), strcat, strcpy() does not check boundary by itself in C and C++. Thus there are chances to throw error.
Example: strcpy(destination, source)
If the size of destination is smaller than source, then it will create an bound error since c or c++ does not check the boundary.
To avoid this, it is always necessary to place and check the length of the string then perform any operation.
Always check the length of the string and then try to access
Situation 2: While reading input
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
In the above program if the user enters a name which is of size greater than 20, definetly the program will crash. So we must ensure by providing proper instruction since it is highly difficult to avoid error.
Way 1:
If you have to programatically obtain the input, you can obtain input in another array which is of bigger size length and then check the length and store it in the required variable.
Way 2:
int main()
{
char str[5];
printf(fgets(str, 5, stdin)); // 5 is the size required
}
fgets() will ensure that only the acceptable length will be
obtained and all other will be truncated without any error. So
strings can be handled efficiently without error during input using
fgets().