I came across a strange behaviour of C with while loop today.
A very simple code :
int userLogin()
{
struct User user;
while (1)
{
printf("\n\nEnter username (or quit to return back) - ");
char userName[50];
scanf("%s", userName);
if (strcmp(userName, "quit") == 0)
{
printf("\nReturning to Login menu...\n");
return 2;
}
printf("\n\nEnter Password - ");
char password[50];
scanf("%s", password);
user = login_user(userName, password);
if (strcmp(user.userID, userName) != 0 ||
strcmp(user.password, password) != 0)
{
printf("\nInvalid username or password !\n");
}
else
{
printf("\nLogin successful...Entering Library menu !\n");
currentUser = user;
if (currentUser.role == 1)
{
libraryOptions();
}
else
{
adminPanel();
}
break;
}
}
}
Now this gives out Segmentation fault (Core Dumped).
However, same code, I just insert a print statement before while(1) :
And suddenly it starts working...
Can somebody help me understand the reason for this ? What am I missing here ?
PS: I know what segmentation fault is, what I need to understand is what changes if I include a print statement.
PPS: struct User is in a header file
struct User {
char *userName; //User name
char *userEmail; //Usre email
char *userID; // user id
char *password; //password
int role; //1 for regular user and 2 for admin
};
login_user is also in another C file which includes the user header file:
struct User login_user(const char *userName, const char *password)
{
int i;
struct User user;
user.userName = "";
user.password="";
if (allUsers.length == 0)
{
return user;
}
for (i = 0; i < allUsers.length; i++)
{
if (strcmp(userArray[i].userID, userName) == 0 &&
strcmp(userArray[i].password, password) == 0)
{
user.userName = userArray[i].userName;
user.password = userArray[i].password;
user.userEmail = userArray[i].userEmail;
user.userID = userArray[i].userID;
user.role = userArray[i].role;
return user;
}
}
return user;
}
I still reiterate that I don't want the answer to main code or reason to segmentation fault (I am working on it), all I request is someone to explain the reason why the print statement makes the code work.