Can you please identify the buffer overflow problems in this java code and expla
ID: 3763206 • Letter: C
Question
Can you please identify the buffer overflow problems in this java code and explain how to fix each one. Thank you.
---------------------------------------------------------------------------------------------------
import java.util.*;
public class Overflow {
static final int INPUT_SIZE = 10;
public static void main(String[] args) {
char[] vals = new char[INPUT_SIZE];
Scanner scan = new Scanner(System.in);
String s1 = getString(scan);
copyVals(s1, vals);
String sub = getSubstring(scan,vals);
System.out.println("sub string: " + sub);
}
public static String getString(Scanner scan) {
System.out.print("Please type a string: ");
String s = scan.nextLine();
return s;
}
public static void copyVals(String s, char[] vals) {
for (int i = 0; i < s.length(); i++) {
vals[i] = s.charAt(i);
}
}
public static String getSubstring(Scanner scan, char[] vals) {
System.out.print("Starting point: ");
int start = scan.nextInt();
System.out.print("Ending point: ");
int end = scan.nextInt();
char[] newChars = getChars(start, end, vals);
return new String(newChars);
}
public static char[] getChars(int start,int end,char[] vals) {
int sz = end - start;
char[] result = new char[sz];
for (int i = 0; i < sz; i++) {
result[i] = vals[start + i];
}
return result;
}
}
Explanation / Answer
there is a problem with this line
String s1 = getString(scan);
in java buffer overflow is automatically handled and it will raise an exception whenever a buffer overflow happens in the code.
to fix the above line we can ask user for the size of the string and then allow the user to proceed with the input.
int count;
Scanner sc= new Scanner(System.in);
System.out.println("size of the string which you want to enter");
count=sc.nextInt();
if(count>INPUT_SIZE)
{
while(1)
{
System.out.println("Invalid input.Enter again.");
count=sc.nextInt();
if (count<INPUT_SIZE)
break;
}
{
else
{
//no need to add here.condition is met.
}
String s1 = getString(scan);
copyVals(s1, vals);
Similar problem is there in getstring function.
there is a problem with getsubstring function also.start and end should be < INPUT_SIZE. we can put the same restriction for them as well.