User Input Program and Analysis
Demonstrate an understanding of C++ programming concepts by completing the following:
#include <bits/stdc++.h> //including libraries.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char text[200];
fstream file;
file.open
("/home/anurag/Desktop/HomeworkLib/CSC450_CT5_mod5.txt",ios::app);
//opening a file in append mode.
cout << "Write text to be written on file." <<
endl;
cin.getline(text, sizeof(text)); //getting user input
// Writing on file
file << text << endl;
file.close();
file.open ("/home/anurag/Desktop/HomeworkLib/CC450-mod5_2.txt", ios::in |
ios::out); // opeing CC450-mod5_2.txt file.
char c;
string s;
file >> s;
while( file.get(c) ) // for each char, including white
spaces.
s += c ;
// Reverse str[beign..end]
reverse(s.begin(), s.end()); //Reversing the content of the
file.
file.close();
file.open ("/home/anurag/Desktop/HomeworkLib/CSC450-mod5-reverse.txt",
ios::app); //Opeing the CSC450-mod5-reverse.txt file.
file << s << endl; //writing the rerersed characters to
file.
file.close(); // closing the file.
return 0;
}
The most common vulnerability that may occur while handling files is the buffer overflow and string manipulation and that may result in a segmentation fault.
1- for e.g.-> gets() function does not check the buffer length and can be vulnerable.
Mitigation: Use fgets() function instead of gets().
2- The functions like strcpy(), strcmp(), strcat() are all vulnerable. These functions do not check the buffer size and may result in a buffer overflow.
Mitigation: use strncpy instead of strcpy, which prevents buffer overflows, but does not guarantee '\0'-termination.
3- sprintf() does not check the buffer length and can result in the buffer overflow.
Mitigation: Use snprintf instead of sprintf. It has two advantages. First, prevent buffer overflows. Second, it returns the minimal size of the buffer needed to fit the whole formatted string.
4- Be careful while opening the file. It can be sometimes vulnerable.
Mitigation: Avoid the race condition by accessing directly the file, and don't overwrite it if it already exists.
A possible problem that can occur in string manipulation of data can be while reading a file the string can terminate if whitespace occurs. So, we have to make sure that whitespaces are covered while reading a file.
User Input Program and Analysis Demonstrate an understanding of C++ programming concepts by completing the following:...