90.8k views
3 votes
Consider the following code snippet:

#include

void simple (char *bar) {

char MyArray[12];

strcpy(MyArray, bar); // copies bar in MyArray --> Myarray==bar }

}

This code snippet (simplified syntax for clarity) takes an argument from the command line and copies it to a local variable Myarray. Myarray is a string of size 12. The size of bar is not bounded

1. When/how could buffer overflow occur? Explain in a few words what input should be entered to cause overflow. You can use an example for clarity.

2. What could be done to prevent the buffer overflow problem? Please explain (It is fine to be succinct but please enter full sentences for full points).

User Geekt
by
5.5k points

1 Answer

3 votes

Answer:

1. Buffer could be overflowed when input entered by user in command line is greater than size 12 it may of size 13 or larger.

for example: when user enters the string 'dolatsinghsodha' than the size of that string stored in bar variable will be 15 as it not size bounded but when it stored in MyArray[12] than it will overflow the buffer for array because MyArray[] is input bounded to maximum 12 characters.

2. There are two ways to prevent buffer overflow

i) make bar varaible input bounded to 12 characters or

ii) assign MyArray[] size at dynamic time

or change code to following state:

void simple (char *bar) {

int a=bar.length

char MyArray[a];

strcpy(MyArray, bar); // copies bar in MyArray --> Myarray==bar }

}

but it in not possible in some languages and platforms

or we can ask user

User Brunns
by
5.1k points