All I am trying to do is ask for a password and print out an error message if the input is longer than 10 characters. It works if the first input is shorter than 10 characters. It just prints out the input and exits the program. If the input is longer than 10 characters the error message prints and it asks for a new password, but if the input is less than 10 characters on the second try it prints out the input and then the program breaks with a "Thread:1 signal SIGABRT" error. I know that I shouldn't be using gets, but I am trying to find a way to make my code work using it.
#include <stdio.h>
#define BUFFER_LENGTH 11
int main() {
int cont;
while (1) {
char line[BUFFER_LENGTH];
char *p;
printf("Enter Password: ");
p = gets (line);
if (strlen(p)>10) {
printf("Error! Password must be shorter than 10 characters! \n");
}else{
printf(p);
printf("\n");
break;
}
}
}
gets()which has been removed from C standard. usefgets()instead.gets. If the user enters more than 10 characters, thengetswill write past the end ofline. If you usefgets, then you can tell it how big your buffer is, which is the only way to protect against this problem (using a larger buffer merely makes the error less likely).printf(p);never ever ever do this!printf("%s", p);instead.