Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

With few changes you can improve the code. You need to replace gets() and strcmp

ID: 3845516 • Letter: W

Question

With few changes you can improve the code. You need to replace gets() and strcmp() with the similar ones bur more safe.

I need help with the strcmp portion.

*/

#include <stdio.h>
#include <string.h>

int main(void)
{
char buffer[4];
int pass_flag = 0;

printf(" Enter the password : ");
gets(buffer);   

if(strcmp(buffer, "pswd"))   
{
printf (" Wrong Password ");
}
else
{
printf (" Correct Password ");
pass_flag = 1;
}

if(pass_flag)
{
/* Now Give root or admin rights to user*/
printf (" Root privileges given to the user ");
}

return 0;
}

Explanation / Answer

#include <stdio.h>
#include <string.h>
int main(void)
{
char buffer[4];
int pass_flag = 0;
printf(" Enter the password : ");
//gets(buffer);
scanf("%s",buffer);
if(strncmp(buffer, "pswd",strlen("pswd")))
{
printf (" Wrong Password ");
}
else
{
printf (" Correct Password ");
pass_flag = 1;
}
if(pass_flag)
{
/* Now Give root or admin rights to user*/
printf (" Root privileges given to the user ");
}
return 0;
}

OUTPUT:


Enter the password :
pswd

Correct Password

Root privileges given to the user

Note:
strncmp you can limit the search, so that it doesn't reach non-accessible memory.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote