How can i start ignoring an if conditional once the condition is met? - performance

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
bool valid(string password);
int main(void)
{
string password = get_string("Enter your password: ");
if (valid(password))
{
printf("Your password is valid!\n");
}
else
{
printf("Your password needs at least one uppercase letter, lowercase letter, number and symbol\n");
}
}
// TODO: Complete the Boolean function below
bool valid(string password)
{
bool CheckUpper = false;
bool CheckLower = false;
bool CheckNumber = false;
bool CheckSymbol = false;
for ( int i=0; i < strlen(password); i++)
{
if (islower (password[i]))
{
CheckLower = true;
}
if (isupper (password[i]))
{
CheckUpper = true;
}
if (isdigit (password[i]))
{
CheckNumber = true;
}
if (!isalnum(password[i]))
{
CheckSymbol = true;
}
}
if (CheckLower == true && CheckUpper == true && CheckNumber == true && CheckSymbol == true)
{
return true;
}
return false;
}
So this code will ask you for a password, and the "valid" Boolean type function will determine whether it is a valid password or not. As you can see it is using an if conditional for every condition required, for each letter of the password in a for loop.
Imagine the first letter is lower case. Is there a way to "skip the if" conditional that checks for a lower case for the next letters/digits of the password? And this way being faster.
I've tried using the continue statement but soon realized it made no sense as it was going back to that if conditional when tenter code herehe for loop advanced one position.

Related

g++ optimizes out nullpointer checks

I have a function that is working if I compile with O0 flag but crashes on a function called on a nullptr if compiled with O2.
If I add some macros to disable optimizations around that function it will work properly.
https://i.imgur.com/ObYiiEl.png
if (LPPARTY pkParty = GetParty())
{
struct FPartyBuff
{
const CSkillProto* pkSk;
DWORD casterPID;
int iAmount1, iDur1;
int iAmount2, iDur2;
FPartyBuff(const CSkillProto* pkSkill, DWORD caster, int amount1, int dur1, int amount2, int dur2)
: pkSk(pkSkill), casterPID(caster), iAmount1(amount1), iDur1(dur1), iAmount2(amount2), iDur2(dur2) {}
void operator() (LPCHARACTER ch)
{
bool bOverride = true;
if (ch && ch->GetPlayerID() != casterPID)
{
if (pkSk->bPointOn != POINT_NONE)
{
ch->AddAffect(pkSk->dwVnum, pkSk->bPointOn, iAmount1, pkSk->dwAffectFlag, iDur1, 0, bOverride, false, casterPID);
bOverride = false;
}
if (pkSk->bPointOn2 != POINT_NONE)
{
ch->AddAffect(pkSk->dwVnum, pkSk->bPointOn2, iAmount2, pkSk->dwAffectFlag, iDur2, 0, bOverride, false, casterPID);
bOverride = false;
}
}
}
};
if (pkVictim && pkParty->IsMember(pkVictim->GetPlayerID()))
{
FPartyBuff f(pkSk, GetPlayerID(), iAmount, iDur, iAmount2, iDur2);
pkParty->ForEachNearMember(f);
}
}
But without them this part of the code calls IsMember on pkParty even when it is a nullpointer.
LPPARTY is defined as CParty*
Why is it happening?

Error in code when searching through the right subtree in my binary search tree

In one of my classes at Uni we are creating Binary search trees and inserting data and looking them up. My code make sense in my head and because of this I cannot find the error anywhere. I have spent ages trying to find the error but cannot find it anywhere. The only thing that might be causing an error is that the precompiled headers didn't work when I started so i removed them from my project. The error only occurrs when i try to use the BST.Lookup and choose a key that is on the right subtree.
This is my main cpp file:
// BinarySearchTrees.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "BST.h"
#include <iostream>
#include <fstream>
#include <string>
void ReadFile(BST &Bst)
{
int iKey;
std::string Key;
std::string Data;
std::ifstream testFile("Test.txt");
if (testFile.is_open())
{
while (!testFile.eof())
{
getline(testFile, Key, ' ');
getline(testFile, Data);
iKey = stoi(Key);
Bst.Insert(iKey, Data);
}
}
}
int main()
{
std::string Option;
int Choice;
BST BST;
//ReadFile(BST);
BST.Insert(6, "Oscar");
BST.Insert(20, "Ben");
BST.Insert(99, "James");
BST.Insert(1, "Alex");
while (Option != "exit")
{
std::cout << "If you wish to Lookup a Node, Insert value to find. Enter 'exit' to close" << std::endl;
getline(std::cin, Option);
if (Option == "exit")
break;
else
{
Choice = stoi(Option);
BST.Lookup(Choice);
}
}
return 0;
}
I believe that the readfile code may be incorrect but am unsure.
My Binary Search Tree Class:
#include "BST.h"
struct BST::Node {
Key key;
Item item;
Node* leftChild;
Node* rightChild;
Node(Key, Item);
};
void BST::Insert(Key inputKey, Item inputItem)
{
Node* previousNode = nullptr;
if (root == nullptr)
{
root = new Node(inputKey, inputItem);
}
else
{
InsertRec(inputKey, inputItem, root, previousNode);
}
}
void BST::InsertRec(Key inputKey, Item inputItem, Node* & Current, Node* & previousNode)
{
if (Current != nullptr)
{
previousNode = Current;
}
bool isLeft = false;
if (!isLeaf(Current))
{
if (inputKey > Current->key)
{
isLeft = false;
InsertRec(inputKey, inputItem, Current->rightChild, previousNode);
}
else if (inputKey < Current->key)
{
isLeft = true;
InsertRec(inputKey, inputItem, Current->leftChild, previousNode);
}
else
{
Current->item = inputItem;
}
}
else
{
Current = new Node(inputKey, inputItem);
if (isLeft)
{
previousNode->leftChild = Current;
}
else
{
previousNode->rightChild = Current;
}
}
}
BST::Item* BST::Lookup(Key soughtKey)
{
Item* Item = LookupRec(soughtKey, root);
std::string Display = /*std::to_string(soughtKey) + ": " + */ *Item;
std::cout << Display << std::endl;
return Item;
}
BST::Item* BST::LookupRec(Key soughtKey, Node* currentNode)
{
if (!isLeaf(currentNode))
{
if ((currentNode->key > soughtKey))
{
LookupRec(soughtKey, currentNode->leftChild);
}
else if ((currentNode->key < soughtKey))
{
LookupRec(soughtKey, currentNode->rightChild);
}
else
{
return &currentNode->item;
}
}
else
{
return nullptr;
}
}
bool BST::isLeaf(Node* n)
{
if (nullptr == n)
{
return true;
}
else
{
return false;
}
}
BST::BST()
{
}
BST::Node::Node(Key K, Item I)
{
key = K;
item = I;
leftChild = nullptr;
rightChild = nullptr;
}
And finally my header file for the binary search tree:
#pragma once
#include "iostream"
#include "string"
class BST
{
public:
using Key = int;
using Item = std::string;
void Insert(Key, Item);
Item* Lookup(Key);
BST();
private:
struct Node;
Node* root = nullptr;
static bool isLeaf(Node*);
static Item* LookupRec(Key, Node*);
static void InsertRec(Key, Item, Node* &, Node* &);
};
Any help would be greatly appreciated. I've been stuck on this for too long and I cannot progress without fixing this first.
The Test.txt file is filled with keys and items that are read and inputted like how I do it manually at the start of my main function, so I dont think the error is the file data.
Thanks in advance
UPDATE: Have finally found the error. The problem was with the bool isLeft in my InsertRec function. The bool was always false due to the recursion so have changed the code to compare previousNode->Key with Current->Key to determine if the child goes left or right

How to prove a C program to LTL formulas with Frama-C Aoraï corresponding to my Promela program?

I have a test Promela program (a model of UI) that can be verified with Spin:
int secrets = 0;
int success = 0;
int fails = 0;
int total = 0;
//variables to control
bool windowLogin = false;
bool windowSecret = false;
bool windowNoSecret = false;
//ltl formulas
ltl secret_to_success_password { [] (secrets<=success)}
ltl check_total { [] (total == success + fails || total + 1 == success + fails)}
ltl we_open_nosecret { <> (windowNoSecret) }
ltl we_open_secret { <> (windowSecret) }
ltl we_open_any { [] <> (windowSecret || windowNoSecret)}
ltl login_check { <> windowLogin -> <> windowSecret}
ltl no_secret_nosecret { [] !(windowSecret && windowNoSecret) }
//channels
chan login=[0] of {short};
chan nonsecret = [0] of {short};
chan secret = [0] of {short};
//main
active proctype MainWindow(){
int buf;
printf("Main started");
do
//infinite loop
:: {
printf("Main: go to Login window");
login! 1;
login? buf;
if
:: buf == 1 -> {//ok
success++;
printf("Main: open secret window");
//"open" secret
secret ! 1;
secret ? buf;//и ждем его
}
:: buf == 0 -> {//fail
fails++;
printf("Main: open nosecret window");
//"open" nonsecret
nonsecret ! 1;
nonsecret ? buf
}
fi
}
od
}
active proctype LoginWindow(){
int buf;
printf("Login started");
do
:: {
login? buf;
windowLogin = true;
if
::true-> { printf("Login fail"); windowLogin = false; login ! 0 }
::true-> { printf("Login fail"); windowLogin = false; login ! 0 }
::true-> { printf("Login ok!"); windowLogin = false; login ! 1 }//p= 1/3
fi
}
od
}
active proctype NonSecretWindow(){
int buf;
printf("Non Secret started");
do
:: {
nonsecret ? buf;
printf("Non Secret window opened");
windowNoSecret = true;
total++;
windowNoSecret = false;
nonsecret ! 1;
printf("Non Secret window closed");
}
od
}
active proctype SecretWindow(){
int buf;
printf(" Secret started");
do
:: {
secret ? buf;
printf("Secret window opened");
windowSecret = true;
secrets++;
total++;
windowSecret = false;
secret ! 1;
printf("Secret window closed");
}
od
}
Then I created a corresponding C program (for first step, without a loop in Main Window):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool windowLogin = false;
bool windowNoSecret = false;
bool windowSecret = false;
int total = 0;
int secrets = 0;
int success = 0;
int fails = 0;
int LoginWindow();
int NonSecretWindow();
int SecretWindow();
int MainWindow() {
//printf("Main started\n");
{
//printf("Main: go to Login window\n");
int r = LoginWindow();
if (r == 1) {
//printf("Main: open secret window\n");
success++;
SecretWindow();
} else {
//printf("Main: open nosecret window\n");
fails++;
NonSecretWindow();
}
}
return 0;
}
int LoginWindow() {
//printf("Login started\n");
windowLogin = true;
if (rand() %3 ==0) {
// windowLogin = false;
return 1;
} else {
// windowLogin = false;
return 0;
}
return 0;
}
int NonSecretWindow() {
//printf("Non Secret started\n");
//printf("Non Secret window opened\n");
windowNoSecret = true;
total++;
//windowNoSecret = false; --- aorai will controll the variable change only in the end of function
//printf("Non Secret window closed\n");
return 0;
}
int SecretWindow() {
//printf("Secret window opened\n");
windowSecret = true;
secrets++;
total++;
//windowSecret = false;
//printf("Secret window closed\n");
return 0;
}
int main() {
MainWindow();
return 0;
}
I want to try using Aoraï LTL (don't want to create .ya by hand) in Frama-C and WP plugins.
First, I created a .ltl file
CALL(main) && _X_ (CALL (MainWindow) && _X_ (CALL (LoginWindow) && _X_ (RETURN (LoginWindow) &&
((_X_ (CALL(NonSecretWindow)))||(_X_ (CALL(SecretWindow)))))))
and can get 2 unknown goals:
[wp] [Alt-Ergo] Goal typed_MainWindow_call_NonSecretWindow_pre : Unknown (Qed:3ms) (81ms)
[wp] [Alt-Ergo] Goal typed_MainWindow_call_SecretWindow_pre : Unknown (Qed:4ms) (79ms)
Also I tried
CALL(main) && _X_ (CALL (MainWindow) && _X_ (CALL (LoginWindow) && _X_ (RETURN (LoginWindow) &&
((_X_ (CALL(NonSecretWindow)||CALL(SecretWindow)))))))
with the same result.
This one
CALL(main) && _X_ (CALL (MainWindow) && _X_ (CALL (LoginWindow) && _X_ (RETURN (LoginWindow) && (
(_F_ (CALL(NonSecretWindow)||CALL(SecretWindow)))))))
can be proved, but I belive that that one should be not correct:
CALL(main) && _X_ (CALL (MainWindow) && _X_ (CALL (LoginWindow) && _X_ (RETURN (LoginWindow) &&
((_F_ (CALL(NonSecretWindow)))))))
but it is correct (all goals were proved).
Also, I tried to test my LTL formulas like in Promela (without CALL/RETURN/X):
_G_ (windowLogin => _F_ (windowSecret || windowNoSecret))
and I got a lot of unproved goals or even for testing
_G_ (total == success + fails || total + 1 == success + fails)
an internal error
[aorai] Welcome to the Aorai plugin
[aorai] failure: Term cannot be transformed into exp.
[kernel] Current source was: test_ltl.c:112
The full backtrace is:
Raised at file "src/libraries/project/project.ml", line 402, characters 50-57
Called from file "src/plugins/aorai/aorai_register.ml", line 385, characters 4-31
...
I use the commandline
rm test_ltl_annot.c
frama-c test_ltl.c -aorai-ltl test_ltl.ltl
frama-c -wp test_ltl_annot.c
and Frama-C version is Phosphorus-20170501.
How should I use this plugin to verify my test program with respect to LTL?

CAPL typedef bool

Does CAPL support something like typedef? My goal is to create a boolean:
typedef char bool;
I am able to do this:
enum bool {
false = 0,
true = 1
};
but it isn't what I was going for because I have to do:
enum bool isValid()
instead of:
bool isValid()
Unfortunately there is no typedef in CAPL.
enum is the closest you can get regarding boolean values.
The following code shows the usage of such enum:
variables
{
enum Bool {
true = 1,
false = 0
};
}
on Start {
enum Bool state;
// setting the value
state = true;
// accessing the integer value
write("state (integer value): %d", state); // prints "1"
// accessing the value identifier
write("state (value identifier ): %s", state.name()); // prints "true"
// usage in if-statement
if (state == true) {
write("if-statement: true");
} else {
write("if-statement: false");
}
// usage in switch-statement
switch (state) {
case true:
write("switch-statement: true");
break;
case false:
write("switch-statement: false");
break;
default:
write("switch-statement: undefined");
break;
}
}

Debug Assertion Error as soon as I take the input. Something wrong with "delete"?

I am having debug assertion error as soon as I input two elements. The program was giving me access reading or sometimes writing violation error after taking 7-8 entries but after I deleted the dynamic array, it is showing debug assertion failed after taking first two inputs and breaks down. Any idea for how to solve it? I am copying only my air class here. I have similar Fire, earth and water classes too.
The error is BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Someone else too asked this question but i can't figure out My program errors. Kindly help would be appreciated.
#ifndef AIR_H
#define AIR_H
#include <iostream>
#include <string>
#include "element.h"
using namespace std;
class Air :public Element
{
public:
string air;
string Elements [2];
int i;
string *elements;
public:
Air(string n): Element (n)
{
air = n;
i=-1;
elements = new string[2];
}
void alreadyExists (string a)
{
int lineCount = 0;
ifstream read;
read.open ("Air.txt", ios::in | ios::app);
while(!read.eof())
{
string x;
read>>x;
lineCount++;
}
lineCount--;
read.close();
read.open("Air.txt", ios::in|ios::app);
for(int i = 0; i < lineCount; i++)
{
read>>elements[i];
}
bool Found = false;
for(int i = 0; i < lineCount; i++) {
if(a == elements[i])
{
Found = true;
break;
}
}
if(!Found)
{
write2file (a);
}
}
void write2file (string air)
{
ofstream write;
write.open ("Air.txt", ios::out|ios::app);
{
write<<air<<endl;
}
}
void DisplayA ()
{
/*for(int i=0; i<2; i++)//( to read through the arrays )
{
cout<<Elements[i]<<endl;
}*/
ifstream read ("Air.txt", ios::in|ios::app);
int i=0;
while (read >> Elements[i])
{
cout<<Elements[i]<<endl;
}
}
Air operator+(Air & air)
{
Air newElement ("NULL");
if (this->air == "Air"||this->air=="air"&& air.air == "Air"||air.air=="air")
{
newElement.air = "Pressure";
cout<<"Yay!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else if ((this->air == "Air"||this->air == "air") && (air.air == "Pressure"||air.air=="pressure"))/* || ((this->air == "Pressure"||this->air=="pressure") && ( air.air == "Air"||air.air=="air")))*/
{
newElement.air = "Atmosphere";
cout<<"Wuhooo!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else return newElement;
}//pressure, atmosphere
~ Air ()
{
delete []elements;
}
};
#endif
BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Assertion means a corrupt heap at deleting/clearing.
As far as I see, you missed the virtual deconstructor of Element.
Try something like:
virtual ~Element() {}
in class Element.
And please post also the Element class.
Good luck!

Resources