In: Computer Science
The following code takes in a command line argument and copies it into a buffer before working on it. Explain in detail any problems that you see in the following C code and how you would fix it. Note only describe how you would fix it, do not actually rewrite or give me another version of the code.
void bad_function(char *input)
{
char dest_buffer[32];
char input_len = strlen(input);
if (input_len < 32) {
strcpy(dest_buffer, input_len);
printf(“Command line argument is %s.\n”,dest_buffer);
}
else {
printf(“Error - input is too long for buffer.\n”);
}
// Works with the dest_buffer here
}
Please up vote ,comment if any query . Thanks for Question . Be safe .
Answer :
strcpy(dest_buffer, input_len); //error line
strcpy(dest_buffer, input); //this will fix program
Explanation :
strcpy function copy data of source char array to destination array .
strcpy(destination array ,source array)
both argument should be array not some not variable
but in above program we are passing a char variable instead of char array .
strcpy(dest_buffer,input) //source and destination argument are char array .
now code will copy input array or command line array to dest_buffer array if length of input array is less than 32 .
Fixed Code :
void bad_function(char *input)
{
char dest_buffer[32];
char input_len = strlen(input);
if (input_len < 32) {
strcpy(dest_buffer, input);
printf("Command line argument is %s.\n",dest_buffer);
}
else {
printf("Error - input is too long for buffer.\n");
}
// Works with the dest_buffer here
}
Please up vote ,comment if any query .