Reputation: 115
I'm trying to write a code to check a password for an uppercase letter. When I type a password with an uppercase letter, the program runs as expected (prints out '1' and the entered password). However, if I type a password without an uppercase letter, the program crashes.
My code:
#include < stdio.h >
#include < stdlib.h >
#include < ctype.h >
#include < string.h >
#include <math.h>
int main() {
char password[100];
int i = 0;
int upper = 0;
printf("Enter a password with an uppercase letter: ");
scanf("%s", password);
for (i = 0; i <= 100; i++) {
if (isupper(password[i])) {
upper = 1;
break;
}
}
printf("%d\n", upper);
printf("%s\n", password);
system("pause");
return (0);
}
The errors:
Debug Assertion Failed!
Program: ...15\Projects\ConsoleApplication3\Debug\ConsoleApplication3.exe File: minkernel\crts\ucrt\src\appcrt\convert\isctype.cpp Line: 36
Expression: c >= -1 && c <= 255
For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application) ConsoleApplication3.exe has triggered a breakpoint.
Debug Assertion Failed!
Program: ...15\Projects\ConsoleApplication3\Debug\ConsoleApplication3.exe File: minkernel\crts\ucrt\src\appcrt\convert\isctype.cpp Line: 42
Expression: c >= -1 && c <= 255
For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application) ConsoleApplication3.exe has triggered a breakpoint.
The program '[13188] ConsoleApplication3.exe' has exited with code 0 (0x0).
Upvotes: 0
Views: 7009
Reputation: 44246
Change this:
for (i = 0; i <= 100; i++) {
to
for (i = 0; i < 100 && password[i] != '\0'; i++) {
^^^ ^^^^^^^^^^^^^^^^^^
note: no = check for end of string
You have
char password[100];
so the legal index is only 0 to 99. Further you need to check if you have reached end of string (aka password[I] != '\0')
A better way of doing what you want to achieve (inspired by @Jean-Francois Fabre):
scanf("%99s", password);
^^
To prevent buffer overflow
for (i = 0; i < strlen(password); i++) {
....
Upvotes: 2
Reputation: 51
change :
for (i = 0; i <= 100; i++)
to :
for (i = 0; i < strlen(password); i++)
Note : You are going out of bound if there is no uppercase letter.
Upvotes: 0