Password Function Error - c

void main()
{
Password();
}
void Password()
{
//declare local variables//
char cPassCode[] = "String";
int iFlag, iComparison = 0;
//Run the code to check the password//
while (iFlag = 1)
{
printf("Please enter the password: ");
scanf("%s", cPassCode);
iComparison = strcmp(cPassCode,"A23bc5");
if (iComparison == 0)
{
Header();
ArrayPrinter(Array);
iFlag = 0;
}
else
{
printf("Wrong password");
iFlag = 1;
}
}
}
I've got this code for my program. The whole program runs fine but it goes through the loops again. I think it has to do with my while loop. If I try changing the condition, the program doesn't run at all. Any ideas?

One problem is here: while (iFlag = 1) you're not comparing iFlag to 1, you're setting it to 1. One correct way to do this is while (iFlag == 1) but a safer way to phrase that is: while (1 == iFlag) so that the compiler will pick up when you make the ==/= error next time. But the best way of all, since iFlag is being used as a boolean, is to simply do while (iFlag)
Next, you need to initialize iFlag before you use it:
int iFlag = 1, iComparison = 0;
And finally, this is not a good way to initialize cPassCode:
char cPassCode[] = "String";
As you don't know how many characters the user will type in -- use a larger value, something like:
#define MAXIMUM_INPUT_SIZE 1024
// ...
char cPassCode[MAXIMUM_INPUT_SIZE];

Your while loop sets iFlag = 1, so it is always true. You want the comparison operator instead iFlag == 1. Also, you should initialize iFlag to 1 instead of zero so that your new loop works. Lastly, you should malloc cPassCode, though that isn't making your program crash (probably).

Related

C project for fun

I am new to coding (I just started this year), so please forgive me for any dumb mistakes. However, my goal is to make some straightforward code to have users enter their username and password. I would like the username to have 8 characters,1 uppercase, 1 lowercase, 1 digit, and 1 symbol. I thought my code was good but I keep running into an issue where I keep getting an error that says, "array must be initialized with a brace enclosed initializer". If you can find where I can improve, and what the issue might be it would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
char username[20];
char password[20];
bool verify_password(char *password)
{
int length = strlen(password);
if (length < 8) return false;
bool has_upper = false;
bool has_lower = false;
bool has_digit = false;
bool has_symbol = false;
for (int i = 0; i < length; i++)
{
if (isupper(password[i])) has_upper = true;
if (islower(password[i])) has_lower = true;
if (isdigit(password[i])) has_digit = true;
if (ispunct(password[i])) has_symbol = true;
}
if (!has_upper) return false;
if (!has_lower) return false;
if (!has_digit) return false;
if (!has_symbol) return false;
return true;
}
int main()
{
printf("please enter your new username:\n");
scanf("%s", username);
printf("please enter your password(must be 8 characters,1 uppercase, 1 lowercase, 1 digit, and 1 symbol):\n");
scanf("%s", password);
char password[strlen(password)] = password;
bool result = verify_password(password);
if (result)
{
printf("password has been verified\n");
}
else
printf("missing element described");
printf("welcome to your account %s!, your password is %s", username, password);
return 0;
}
The compiler is saying that arrays need to be initialized with = { ... };
char password[strlen(password)] is an array, specifically a variable-length array (VLA). However, these arrays are special since they cannot get initialized at all. You have to set their values at run-time
Furthermore, it has to be char password[strlen(password)+1] so there's room for the null terminator.
Furthermore, you need to assign a value to a string using strcpy, not with the = operator.
Furthermore, you cannot have several variables with the same name. Or well you can, but in case of char password[strlen(password)] = password;, the password refers to the local variable, not the global one. It's a bad idea to use global variables in general and this would be one of many reasons why.
Overall you cannot do C programming by trial & error. There's no "take a chance and type something that looks ok", you need to actually know what every single thing you write does and that it is valid C.

Identify User Defined Function and Library Defined Function

I'm given a task to write a program that checks a piece of code, maximum of 20 lines of code, when the program runs you type in a function name, number of lines of code and type in the codes.
It's meant to search in the code and return if the function name you entered is a Library Function or User Defined Function or No Function if it doesn't find it, the code I've written is below, it doesn't work because I made mistakes and I've been trying to fix it but can't seem to figure it out, and I tried debugging to see where I made mistake, and I figured that in the function SearchRealisation it returns an error that
Run-Time Check Failure #2 - Stack around the variable 'buff' was
corrupted.
This program sample returns Library function instead of user defined function
type the function name: addition
Get count string in code: 9
int addition(int num1, int num2)
{
int result = num1 + num2; //trial
return result;
}
int main()
{
addition(8, 9);
}
Output is Library Function but correct output should be User Defined Function since it was defined in the code
void InputText(int length, char Text[MAX_STRINGS][MAX_COLUMNS])
{
//Repeat by Count String
gets_s(Text[0]);
for (int i = 0; i < length; i++)
gets_s(Text[i]);
//Output a string (starting with � zero and ending with Count String-1)
}
void OutMesseg(int param)
{
//Display one of three messages according to the parameter
if (param == -2)
printf("%s", "user defined function");
else if (param == -1)
printf("%s", "no function");
else
printf("%s", "library function");
}
char* DeleteComentsInString(char Text[MAX_STRINGS], char New[MAX_STRINGS])
{
char* a = strstr(Text, "//");
int len = strlen(Text);
if (a != NULL) len -= strlen(a);
strncpy(New, Text, len);
New[len] = '\0';
return New;
}
bool IsTypeC(char Word[MAX_STRINGS])
{
char ctype[6][MAX_STRINGS] =
{
"int",
"bool",
"char",
"float",
"double",
"void"
};
for (int i = 0; i < 6; i++)
{
if (strstr(Word, ctype[i]) != 0)
return true;
}
return false;
}
int SearchRealisation(int length, char Text[MAX_STRINGS][MAX_COLUMNS], int index_fanc, int& end)
{
int count = 0;
int start = -1;
end = -1;
char buff[MAX_STRINGS];
//Find first {
for (int i = index_fanc + 1; i < length && !count; i++)
{
if (strstr(DeleteComentsInString(Text[i], buff), "{") != NULL)
{
count++;
start = i;
}
}
//find last }
for (int i = start + 1; i < length && count; i++)
{
if (strstr(DeleteComentsInString(Text[i], buff), "{") != NULL)
count++;
else if (strstr(DeleteComentsInString(Text[i], buff), "}") != NULL)
count--;
if (!count)
end = i;
}
if (end == -1)
start = -1;
else
return start;
}
int SearchFunction(int length, char Text[MAX_STRINGS][MAX_COLUMNS], char FunctionName[MAX_COLUMNS], int& end)
{
//bool flag = false;
char commentDel[120];
int in;
for (int i = 0; i < length; ++i)
{
DeleteComentsInString(Text[i], commentDel);
if (strstr(commentDel, FunctionName) != NULL)
{
in = strlen(commentDel) - strlen(strstr(commentDel, FunctionName));
if ((in == 0 || (in != 0 && commentDel[in - 1] == ' ')) && (commentDel[in + strlen(FunctionName)] == ' ' || commentDel[in + strlen(FunctionName)] == '(') && strstr(commentDel, ";") == NULL)
{
return SearchRealisation(length, Text, i, end);
}
}
}
end = -1;
return -1;
}
int SearchResult(int length, char Text[MAX_STRINGS][MAX_COLUMNS], char FunctionName[MAX_COLUMNS])
{
int index;
int end;
int start = SearchFunction(length, Text, FunctionName, end);
if (start == -1)
return -1;
index = SearchFunction(length, Text, FunctionName, end);
if (index < 0)
return -2;
return index;
}
int findFunction(char string[MAX_STRINGS][MAX_COLUMNS], char* functName, int M)
{
return 0;
}
int main()
{
int length = 0;
char Code[MAX_STRINGS][MAX_COLUMNS] = { 0 };
char FunctionName[MAX_COLUMNS];
//char ConstantName[MAX_STRINGS];
printf("type the function name: ");
scanf("%s", &FunctionName);
printf("Get count string in code: ");
scanf("%d", &length);
InputText(length, Code);
printf("\n");
OutMesseg(SearchResult(length, Code, FunctionName));
return 0;
}
Well, you have been given a very difficult task:
There's no way to check this, as functions are resolved by a dynamic process that depends on your filesystem state, which is not available at runtime, after you have already compiled your program.
How do you distinguish a function that is compiled in a separate (but user defined) compilation unit from a system defined function? (e.g. double log(double);) that is defined in a math library? There is no way: the linker gets both from a different place (in the first case it gets it from the place you compiled the separate module, in the system case it gets it from a common library directory that has all the system related functions), but you don't have that information available at runtime).
In order to do this task feasible, you'd at least have the full set of source code files of your program. Preprocess them with the cpp(1) preprocessor (so you bypass all the macro expansion invocations) and then check for all function calls in the source code that are not provided in the full set of sources you have. This is quite similar to what the linker does. After compilation, the compiler leaves an object file with the compiled code, and a symbol table that identifies all the unresolved identifiers, and more important all the provided identifiers from this module. The linker then goes on all your modules trying to solve the unknowns, and for each that it doesn't have a solution in your code, it goes to the library directory to search for it. If it doesn't find it in either one, it fails telling you something is wrong.
In my opinion, you have been given a trap task, as the C language preprocess its input (this is something you should do, as many functions are hidden in the internals of macro bodies), then parse the code (for this, you need to write a C parser, which is no trivial task) to select which identifiers are defined in your code and which aren't. Finally you need to check all the calls you do in the code to divide the set in two groups, calls that are defined (and implemented) in your code, and calls that aren't (implemented, all the calls the compiler needs must be defined with some kind of prototype).
It's my opinion, but you have not a simple task, solvable in a short program (of perhaps one hundred lines) but a huge one.
Thanks a lot to everyone that answered I came up with a way to search the code for function definition and thereby return a value if its defined or not, or not even found, might not be the best solution to the task but works so far

Printing an array of structs in C

I'm trying to print an array of structs that contain two strings. However my print function does not print more than two indices of the array. I am not sure why because it seems to me that the logic is correct.
This is the main function
const int MAX_LENGTH = 1024;
typedef struct song
{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
} Song;
void getStringFromUserInput(char s[], int maxStrLength);
void printMusicLibrary(Song library[], int librarySize);
void printMusicLibraryTitle(void);
void printMusicLibrary (Song library[], int librarySize);
void printMusicLibraryEmpty(void);
int main(void) {
// Announce the start of the program
printf("%s", "Personal Music Library.\n\n");
printf("%s", "Commands are I (insert), S (sort by artist),\n"
"P (print), Q (quit).\n");
char response;
char input[MAX_LENGTH + 1];
int index = 0;
do {
printf("\nCommand?: ");
getStringFromUserInput(input, MAX_LENGTH);
// Response is the first character entered by user.
// Convert to uppercase to simplify later comparisons.
response = toupper(input[0]);
const int MAX_LIBRARY_SIZE = 100;
Song Library[MAX_LIBRARY_SIZE];
if (response == 'I') {
printf("Song name: ");
getStringFromUserInput(Library[index].songName, MAX_LENGTH);
printf("Artist: ");
getStringFromUserInput(Library[index].artist, MAX_LENGTH);
index++;
}
else if (response == 'P') {
// Print the music library.
int firstIndex = 0;
if (Library[firstIndex].songName[firstIndex] == '\0') {
printMusicLibraryEmpty();
} else {
printMusicLibraryTitle();
printMusicLibrary(Library, MAX_LIBRARY_SIZE);
}
This is my printing the library function
// This function will print the music library
void printMusicLibrary (Song library[], int librarySize) {
printf("\n");
bool empty = true;
for (int i = 0; (i < librarySize) && (!empty); i ++) {
empty = false;
if (library[i].songName[i] != '\0') {
printf("%s\n", library[i].songName);
printf("%s\n", library[i].artist);
printf("\n");
} else {
empty = true;
}
}
}
I think the problem is caused due to setting : empty = true outside the for loop and then checking (!empty) which will evaluate to false. What I am surprised by is how is it printing even two indices. You should set empty = false as you are already checking for the first index before the function call.
The logic has two ways to terminate the listing: 1) if the number of entries is reached, or 2) if any entry is empty.
I expect the second condition is stopping the listing before you expect. Probably the array wasn't built as expected (I didn't look at that part), or something is overwriting an early or middle entry.
you gave the definition as:
typedef struct song
{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
}Song;
the later, you write if (library[i].songName[i] != '\0') which really seems strange: why would you index the songname string with the same index that the lib?
so I would naturally expect your print function to be:
// This function will print the music library
void printMusicLibrary (Song library[], int librarySize) {
for (int i = 0; i < librarySize; i ++) {
printf("%s\n%s\n\n", library[i].songName,
library[i].artist);
}
}
note that you may skip empty song names by testing library[i].songName[0] != '\0' (pay attention to the 0), but I think it would be better not to add them in the list (does an empty song name make sens?)
(If you decide to fix that, note that you have an other fishy place: if (Library[firstIndex].songName[firstIndex] == '\0') with the same pattern)

C - scanf doesn't stop looping in string input

i'm making a small test to see if a word is inside another, and i want to return the index where that word begins.
Example: if i check "um" inside "amolum" the return value should be 4(position of the leter "u" where the word begins.
This is what my code looks like:
(...)
int cad_look_str (char s1[], char s2[]) {
int indS1 = 0, indS2 = 0;
while (s1[indS1]!='\0'|| s2[indS2]!='\0') {
if (s1[indS1]==s2[indS2]) {
indS1++;
indS2++;
}
else indS1=0;
}
if (s2[indS2]=='\0' && s1[indS1]!='\0') return -1;
else return indS2-strlen (s1);
}
void main () {
char s[100];
char s1[100];
scanf ("%s",s);
scanf ("%s",s1);
printf ("%d \n", cad_look_str(s1,s) );
}
The problem is that when i compile this, it doesn't stop looping on scanf... It just continues to ask for strings.
If i put cad_look_str(s1,s1) on the last line, it works fine... Why is this happening?
Regards
Your initial loop condition will never terminate if the first characters don't match your comparison test within your if statement.
The 'while' loop checks to ensure the current character positions (both 0 on first pass) are non-terminators. If they're not, and they're not equal, indS1 is reset to its starting position. indS2 never changes, thus the while condition is unchanged.
Might look at some other string functions to accomplish your task unless the scanning is a mandatory component for some reason.
Index of second string should be incremented in the else part also.
if (s1[indS1]==s2[indS2])
{
indS1++; indS2++;
}
else {
indS1=0;
indS2++;
}
changed cad_look_str() for situations like s1 : gdgddadada, s2 : dadada
int cad_look_str (char s1[], char s2[]) {
int indS1 = 0, indS2 = 0;
int flag = 0;
while (s1[indS1]!='\0'&& s2[indS2]!='\0') {
if (s1[indS1]==s2[indS2]) {
indS1++;
indS2++;
flag = 1;
}
else
{
indS1=0;
indS2++;
if(flag) indS2--; // to work with srtrings s1: gdgddadada s2: dadada
flag = 0;
}
}
if (s2[indS2]=='\0' && s1[indS1]!='\0') return -1;
else return indS2-strlen (s1);
}

encountered strange situation-variable value

I am programming on some device and I encountered
rather strange situation.
The same variable - for the first time has correct value,
but the SAME variable on a different place in code,
has a DIFFERENT value.
What can be causing this? I am pretty sure I didn't modify
the variable in between, I am also pretty sure I didn't
modify the variable using some pointers accidentally.
What can be causing this? I am really confused?
Can it be related that I for example used whole available stack
space of some function - and because of this compiler automatically
0-ifies my variable(or something similar)?
I have some long code inside a single function f.
Here's whole details on usage of pointsEntered variable in my code (how it is used).
/* Let the user input points */
s32 pointsEntered = 0;
int pointsCounter = 0;
while(1)
{
if(pointsCounter == 3)
return; // User entered wrong points 3 times, exit function
bool retStatus = false;
retStatus = inputPoints(&pointsEntered);
if(false == retStatus) // If user didn't enter amount, exit this function
return;
if(pointsEntered>atoi(userAmount)){
PromptBox(false, 0, "Points should not be more\n than current points");
pointsCounter++;
continue;
}
break;
}
// PROBLEM: pointsEntered - is OK here but as it will be shown below, it gets modified down the way
// even though I don't change it directly
char intTest1[50];
sprintf(intTest1, "1pentered %d", pointsEntered); // Here the value is OK! It shows value that I entered, e.g., 220
PromptBox(false, 0, intTest1);
/* Let the user enter 4 digit pin code */
u8 pinEntered[5] = {0};
bool retStatus1 = false;
retStatus1 = inputPin(pinEntered);
pinEntered[5]='\0';
if(false == retStatus1) // If user didn't enter amount, exit this function
return;
char intTest2[50];
sprintf(intTest2, "2pentered %d", pointsEntered); // Here pointsEnetered is OK
PromptBox(false, 0, intTest2);
/* Compute hash of pin code*/
s32 siRet1 = 0;
u8 pinVerify[25]={0};
u8 hashResult[16] = {0};
memcpy(pinVerify,pinEntered,4);
memcpy(&pinVerify[4],"XXXX",21);
siRet1 = sdkMD5(hashResult,pinVerify,25);
char intTest3[50];
sprintf(intTest3, "3pentered %d", pointsEntered); // Here pointsEntered has changed!!!
PromptBox(false, 0, intTest3);
/* convert string hash code to byte array */
unsigned char val[16] = {0};
unsigned char * pos = pinHash;
size_t count = 0;
// WARNING: no sanitization or error-checking whatsoever
for(count = 0; count < sizeof(val)/sizeof(val[0]); count++)
{
sscanf(pos, "%2hhx", &val[count]);
pos += 2 * sizeof(char);
}
char intTest4[50];
sprintf(intTest4, "4pentered %d", pointsEntered);
PromptBox(false, 0, intTest4);
/* Does the pin hash match ? */
if (siRet == SDK_OK && (!memcmp(hashResult,val,16)))
{
MsgBox("PIN OK","",0,SDK_KEY_MASK_ESC | SDK_KEY_MASK_ENTER);
}
else
{
MsgBox("PIN doesn't match-exiting","",0,SDK_KEY_MASK_ESC | SDK_KEY_MASK_ENTER);
return;
}
char intTest[50];
sprintf(intTest, "pentered %d", pointsEntered);
PromptBox(false, 0, intTest);
These two lines may cause it (as it's undefined behavior):
u8 pinEntered[5] = {0};
...
pinEntered[5]='\0';
Here you declare an array of five entries, but then you assign to a sixth item. This will most likely overwrite any previous variable on the stack.

Resources