Clang++ compiled successfully but executable file didn't run - c++

I ran into this problem when solving a math problem. Here's the code:
// program to check if parentheses expression is correct
// {()}[{()}] = true, ()(} = false
#include <string.h>
#include <iostream>
#include <stack>
using namespace std;
int par(string str) {
int a = str.length();
stack<char> S;
char x;
for (int i = 0; i < a; i++) {
x = str[i];
if (x == '(' || x == '[' || x == '{') {
S.push(x);
} else {
if (x == ')') {
if (S.top() == '(') {
S.pop();
} else
return 0;
} else if (x == ']') {
if (S.top() == '[') {
S.pop();
} else
return 0;
} else if (x == '}') {
if (S.top() == '{') {
S.pop();
} else
return 0;
}
}
}
if (!S.empty()) {
return 0;
} else
return 1;
}
int main() {
int n;
string str;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> str;
cout << par(str) << endl;
}
return 0;
}
Ignore the bad coding, when compile this code using this command:
clang++ -std=c++20 -Wall -Wextra -pedantic -g par.cpp -o par.exe
The code compiled, executable generated, but when I open par.exe it terminates immediately.
But when using g++, it worked well:
g++ -std=c++20 -Wall -Wextra -pedantic -g par.cpp -o par.exe
Here's the clang++ version:
>clang++ --version
clang version 15.0.5
Target: x86_64-w64-windows-gnu
Thread model: posix
InstalledDir: C:/msys64/ucrt64/bin
and g++:
>g++ --version
g++.exe (tdm64-1) 10.3.0
Copyright (C) 2020 Free Software Foundation, Inc.
I'm assumimg this was because of the <stack> and <queue> library, as I used clang without these libraries and it worked well.
Any ideas ?

Related

Undefined reference for TicTacToe [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Using G++ to compile multiple .cpp and .h files
(13 answers)
Closed last year.
I've got this file where it seems to be an undefined reference but I don't know why, everything it seems correct to me. Someone can help me?
This is the error:
g++ -c driver.cpp -std=c++11 -pedantic -Wall
g++ -o driver driver.o
/usr/bin/ld: driver.o: in function `main':
driver.cpp:(.text+0x23): undefined reference to `TicTacToe::TicTacToe()'
/usr/bin/ld: driver.cpp:(.text+0x2f): undefined reference to `TicTacToe::makeMove()'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: driver] Error 1
And these are the files I'm using:
The driver program:
// driver.cpp: use of TicTacToe class
#include "TicTacToe.h" // include definition of class TicTacToe
int main() {
TicTacToe g; // creates object g of class TicTacToe
g.makeMove(); // invokes function makeMove
}
This is the class:
// TicTacToe.h
#ifndef TICTACTOE_H
#define TICTACTOE_H
#include <array>
class TicTacToe {
private:
enum Status {WIN, DRAW, CONTINUE}; // enumeration constants
std::array<std::array<int, 3>, 3> board;
public:
TicTacToe(); // default constructor
void makeMove(); // make move
void printBoard() const; // print board
bool validMove(int, int) const; // validate move
bool xoMove(int); // x o move
Status gameStatus() const; // game status
};
#endif
These are the class function members:
// TicTacToe.cpp
// Member-function defnitions for class TicTacToe.
#include <iostream>
#include <iomanip>
#include "TicTacToe.h" // include definition of class TicTacToe
using std::cout;
using std::cin;
using std::setw;
TicTacToe::TicTacToe() {
for (int j{0}; j < 3; ++j) { // initialize board
for (int k{0}; k < 3; ++k) {
board[j][k] = ' ';
}
}
}
void TicTacToe::makeMove() {
printBoard();
while (true) {
if (xoMove('X')) {
break;
}
else if (xoMove('O')) {
break;
}
}
}
void TicTacToe::printBoard() const {
cout << " 0 1 2\n\n";
for (int r{0}; r < 3; ++r) {
cout << r;
for (int c = 0; c < 3; ++r) {
cout << setw(3) << static_cast< char > (board[r][c]);
if (c != 2) {
cout << " |";
}
}
if (r != 2) {
cout << "\n ____|____|____\n | | \n";
}
}
cout << "\n\n";
}
bool TicTacToe::xoMove(int symbol) {
int x;
int y;
do {
cout << "Player " << static_cast<char>(symbol) << " enter move: ";
cin >> x >> y;
cout << '\n';
} while (!validMove(x, y));
board[x][y] = symbol;
printBoard();
Status xoStatus = gameStatus();
if (xoStatus == WIN) {
cout << "Player " << static_cast<char>(symbol) << " wins!\n";
return true;
}
else if (xoStatus == DRAW) {
cout << "Game is draw.\n";
return true;
}
else { // CONTINUE
return false;
}
}
bool TicTacToe::validMove(int r, int c) const {
return r >= 0 && r < 3 && c >= 0 && c < 3 && board[r][c] == ' ';
}
// must specify that type Status is part of the TicTacToe class.
TicTacToe::Status TicTacToe::gameStatus() const {
// check for a win on diagonals
if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
return WIN;
}
else if (board[2][0] != ' ' && board[2][0] == board[1][1] && board[2][0] == board[0][2]) {
return WIN;
}
// check for win in rows
for (int a{0}; a < 3; ++a) {
if (board[a][0] != ' ' && board[a][0] == board[a][1] && board[a][0] == board[a][2]) {
return WIN;
}
}
// check for win in columns
for (int a{0}; a < 3; ++a) {
if (board[0][a] != ' ' && board[0][a] == board[1][a] && board[0][a] == board[2][a]) {
return WIN;
}
}
// check for a completed game
for (int r{0}; r < 3; ++r) {
for (int c{0}; c < 3; ++c) {
if (board[r][c] == ' ') {
return CONTINUE; // game is not finished
}
}
}
return DRAW; // game is a draw
}
It's probably something stupid but I don't know what I have to look for.
step by step:
g++ -c driver.cpp TicTacToe.cpp -std=c++11 -pedantic -Wall
g++ -o driver driver.o TicTacToe.o
./driver

Memory Heap and Leak Summary on Valgrind

Our school submissions are all through matrix using valgrind, which checks the output line by line. However, when submitting, I'm getting "Memory Error Detected".
Compile result:
Success! No errors or warnings...
Execution:
Script started, file is student_output.txt
Script started, file is student_output.txt
==110143== Memcheck, a memory error detector
==110143== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==110143== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==110143== Command: ms
==110143==
Loading Data
Library Application:
When inputing data:
Publication Title: e
==111103== Conditional jump or move depends on uninitialised value(s)
==111103== at 0x404318: sdds::LibApp::search(int, char) (LibApp.cpp:145)
==111103== by 0x404ABC: sdds::LibApp::removePublication() (LibApp.cpp:329)
==111103== by 0x404DC1: sdds::LibApp::run() (LibApp.cpp:415)
==111103== by 0x404F6F: runLibApp(char const*) (LibAppMain_prof.cpp:9)
==111103== by 0x405084: main (LibAppMain_prof.cpp:20)
==111103==
Other information
I also get error while adding a publication, (using the newPublication() function), which in the same file below.
==140314== Use of uninitialised value of size 8
==140314== at 0x404926: sdds::LibApp::newPublication() (LibApp.cpp:282)
==140314== by 0x404DAA: sdds::LibApp::run() (LibApp.cpp:411)
==140314== by 0x404F6F: runLibApp(char const*) (LibAppMain_prof.cpp:9)
==140314== by 0x405084: main (LibAppMain_prof.cpp:20)
==140314==
==140314== Use of uninitialised value of size 8
==140314== at 0x40493F: sdds::LibApp::newPublication() (LibApp.cpp:284)
==140314== by 0x404DAA: sdds::LibApp::run() (LibApp.cpp:411)
==140314== by 0x404F6F: runLibApp(char const*) (LibAppMain_prof.cpp:9)
==140314== by 0x405084: main (LibAppMain_prof.cpp:20)
==140314==
The file is posted below.
LibApp.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
#include "LibApp.h"
#include "Book.h"
#include "PublicationSelector.h"
namespace sdds {
int NOLP=0;
int LLRN=0;
bool LibApp::confirm(const char* message)
{
Menu conf(message);
conf<<"Yes";
int t_return = conf.run();
if(t_return) return true;
return false;
}
LibApp::LibApp(const char filename[256])
{
m_mainMenu << "Add New Publication"
<< "Remove Publication"
<< "Checkout publication from library"
<<"Return publication to library";
m_exitMenu << "Save changes and exit" << "Cancel and go back to the main menu";
strcpy(m_filename, filename);
m_publicationMenu << "Book" << "Publication" ;
load();
}
LibApp::~LibApp()
{
for (int i = 0; i< NOLP ; i++) {
delete PPA[i];
}
}
void LibApp::load(){
std::cout<<"Loading Data\n";
std::ifstream infile(m_filename);
char type{};
for (int i = 0; infile ; i++) {
infile >> type;
infile.ignore();
if (infile) {
if (type == 'P')
PPA[i] = new Publication;
else if (type == 'B')
PPA[i] = new Book;
else std::cout<<"no data\n";
if (PPA[i] && i < SDDS_LIBRARY_CAPACITY ) {
infile >> *PPA[i];
LLRN=PPA[i]->getRef();
NOLP++;
}
}
}
}
void LibApp::save(){
std::cout<<"Saving Data\n";
std::ofstream outfile(m_filename);
for (int i = 0; i < NOLP; i++) {
if (PPA[i]->getRef()!=0) {
outfile << *PPA[i] << std::endl;
}
}
}
void prnPub(Publication* p[], int size, int ref) {
int i;
for (i = 0; i < size; i++) {
if (ref == p[i]->getRef()) {
std::cout << *p[i] << std::endl;
i = size;
}
}
}
int LibApp::search(int option,char type){
PublicationSelector ps("Select one of the following found matches:", 15);
std::cout<<"Publication Title: ";
char title[256];
std::cin.getline(title,256);
if(option==1)
{
for (int i = 0; i< NOLP; i++) {
if (strstr(*PPA[i],title) && PPA[i]->getRef()!=0 && type==PPA[i]->type())
ps << PPA[i];
}
}
else if(option==2)
{
for (int i = 0; i< NOLP; i++) {
if (strstr(*PPA[i],title) && !PPA[i]->onLoan() && PPA[i]->getRef()!=0 && type==PPA[i]->type())
ps << PPA[i];
}
}
else if(option==3)
{
for (int i = 0; i< NOLP; i++) {
if (strstr(*PPA[i],title) && PPA[i]->onLoan() && PPA[i]->getRef()!=0 && type==PPA[i]->type())
ps << PPA[i];
}
}
int ref = 0;
if (ps) {
ps.sort();
ref = ps.run();
if (ref) {
prnPub(PPA, NOLP , ref);
}
else {
std::cout << "Aborted!\n";
}
}
else {
std::cout << "No matches to found!" << std::endl;
}
return ref;
}
void LibApp::returnPub()
{
std::cout<<"Return publication to the library\n";
int i=m_publicationMenu.run();
char type;
if(i==1) type='B';
else type='P';
int ref=search(3,type);
if(ref!=0 && confirm("Returning publication?"))
{
Date date=getPub(ref)->checkoutDate();
Date today;
int days=today-date;
days-=15;
if(days>0)
{
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout<<"Please pay $"<<float(days)*(0.5)<<" penalty for being "<<days<<" days late!\n";
}
getPub(ref)->set(0);
std::cout<<"Publication returned\n";
m_changed=true;
}
}
void LibApp::newPublication()
{
if( NOLP >= SDDS_LIBRARY_CAPACITY )
{
std::cout<<"Library is at its maximum capacity!\n";
return;
}
std::cout<<"Adding new publication to library\n";
int i=m_publicationMenu.run();
Publication *p=nullptr;
if(i==0)
{ std::cout<<"Aborted!\n";
return;
}
else if(i==1)
{
p = new Book;
std::cin >> *p;
}
else if( i==2 )
{
p = new Publication;
std::cin >> *p;
}
if(std::cin.fail())
{
std::cout<<"\nAborted!\n";
exit(0);
}
if(confirm("Add this publication to library?"))
{
m_changed = true;
PPA[NOLP]=p;
LLRN=PPA[NOLP]->getRef();
NOLP++;
std::cout<<"Publication added\n";
}
if( !*p )
{
std::cout<<"Failed to add publication!\n";
delete p;
}
}
Publication* LibApp::getPub(int libRef)
{
for(int i=0;i<NOLP;i++)
{
if(libRef==PPA[i]->getRef()) return PPA[i];
}
return nullptr;
}
void LibApp::removePublication()
{
//std::cout<<;
std::cout<<"Removing publication from the library\n";
int i=m_publicationMenu.run();
char type;
if(i==1) type='B';
else
{
type='P';
}
int ref=search(1,type);
if(ref!=0 && confirm("Remove this publication from the library?"))
{
m_changed = true;
getPub(ref)->setRef(0);
std::cout<<"Publication removed\n";
}
}
void LibApp::checkOutPub()
{
std::cout<<"Checkout publication from the library\n";
int i=m_publicationMenu.run();
char type;
if(i==1) type='B';
else type='P';
int ref=search(2,type);
if(ref!=0 && confirm("Check out publication?"))
{
m_changed = true;
int mn;
std::cout << "Enter Membership Number: ";
while (1)
{
std::cin>>mn;
if(mn > 9999 && mn <= 99999 ) break;
std::cout<<"Invalid membership number, try again: ";
}
getPub(ref)->set(mn);
std::cout<<"Publication checked out\n";
}
}
LibApp::LibApp()
{
m_mainMenu << "Add New Publication"
<< "Remove Publication"
<< "Checkout publication from library"
<<"Return publication to library";
m_exitMenu << "Save changes and exit" << "Cancel and go back to the main menu";
load();
}
void LibApp::run()
{
while(1)
{
int option = m_mainMenu.run();
if( option == 1 )
{
newPublication();
}
else if( option == 2 )
{
removePublication();
}
else if( option == 3 )
{
checkOutPub();
}
else if( option == 4 )
{
returnPub();
}
else if( option == 0 )
{
if(m_changed)
{
int opn = m_exitMenu.run();
if( opn == 1 )
{
save();
break;
}
else if( opn == 2 )
{
;
}
else if( opn == 0)
{
if(confirm("This will discard all the changes are you sure?"))
break;
}
}
else break;
}
std::cout<<std::endl;
}
std::cout<<std::endl;
std::cout<<"-------------------------------------------\n";
std::cout<<"Thanks for using Seneca Library Application\n";
}
}
Please help me with this. My submission is today idk what the issues are.
Like the error message says:
Conditional jump or move depends on uninitialised value(s)
==111103== at 0x404318: sdds::LibApp::search(int, char) (LibApp.cpp:145)
There is an if-statement (or something logically equivalent to an if-statement) at line 145 of LibApp.cpp that is basing its decision on which path to take on a variable that was never initialized to any value; as such, the behavior of that if-test is undefined (ie if could go either way depending on what arbitrary data happens to be present at that variable’s memory location at the time).
So you’ll need to look at the variable(s) present in the if-test at line 145 to figure out which ones aren’t being set beforehand, and then fix the error by making sure they do get set first.
If necessary, you can add temporary if-tests just to provoke valgrind into giving you more results:
if (some_suspect_var != 0) fprintf(stderr, “Yea\n”);
else fprintf(stderr, “Nay\n”);
… then if you get a valgrind error on that if-line, you know that some_suspect_var is uninitialized at that point.

C++ atomic variable compare and increment

I would like to know how to make the following function in a whole atomic.
With my code, I believe there can be a situation that two threads both pass the condition, and return 0,1 respectively right?
static std::atomic<uintV> shared_v (0);
int compare_increment() {
if (shared_v >= 10) {
return -1;
}
return shared_v++;
Any help would be appreciated.
You can use compare_exchange_weak in a loop to achieve this sort of read-modify-write effect without a mutex.
Example (untested):
int compare_increment() {
uintV old = shared_v.load();
do {
if (old >= 10)
return -1;
} while (!shared_v.compare_exchange_weak(old, old+1));
return old;
}
I wrote one for a bit of fun.
$ cat compare-exchange-atomic-test.cpp
#include <array>
#include <atomic>
#include <iostream>
#include <thread>
std::atomic<int> value{0};
std::atomic<int> loops{0};
int comparison_target = 10;
void f() {
int v;
do {
v = value;
if (v < comparison_target) {
return;
}
++loops;
} while (!value.compare_exchange_weak(v, v + 1));
}
void g() {
int i;
for (i = 0; i < 1000; ++i) {
f();
}
}
int main(int argc, char *argv[]) {
if (argc > 1) {
comparison_target = std::stoi(argv[1]);
}
std::array<std::thread, 64> threads;
for (auto &x : threads) {
x = std::thread(g);
}
for (auto &x : threads) {
x.join();
}
std::cout << value << ' ' << comparison_target << ' ' << loops << std::endl;
return 0;
}
$ g++ -Wall -W -pedantic -g -O3 -flto -fno-fat-lto-objects -mcpu=native -DNDEBUG -pthread -MMD -fPIC -fPIE -std=c++17 compare-exchange-atomic-test.cpp -pthread -flto -fno-fat-lto-objects -o compare-exchange-atomic-test
$ ./compare-exchange-atomic-test 1
0 1 0
$ ./compare-exchange-atomic-test 0
64000 0 455100
$ ./compare-exchange-atomic-test 0
64000 0 550596

How to fix runtime error in Shunting Yard algorithm

I have implemented Shunting yard algorithm using stack in c++.
Well it is working quite well on inputs from SPOJ example inputs but when I input:
1
(((a+b) * (c+r)^(t+b)-n)^(c-(d * e))-b)+(c+(e-(d^r)))
I get a runtime error.
Note: I only get a runtime error when I call infixToPostfix() and use the above input and not when I comment it out.
Submission to SPOJ and running on ideone(with input above) results in a runtime error.
I really can't understand this behaviour of my program, so any help is welcomed.
I have tried some random inputs and it seems to work fine on them.
Even though they had spaces around operators.
#include<iostream>
#include<vector>
#include<math.h>
#include<stack>
#include<strings.h>
using namespace std;
void infixToPostfix(string st);
int pr(char s);
int main() {
int t;
scanf("%d",&t);
cin.ignore();
string st; // input string
while(t--)
{
getline(cin,st);
cin.sync();
cout<<st<<endl;
infixToPostfix(st);
}
return 0;
}
int pr(char s) // to check precedence
{
if(s == '^')
{
return 4;
}
else if(s == '*')
{
return 3;
}
else if(s == '/')
{
return 3;
}
else if(s == '+')
{
return 2;
}
else if(s == '-')
{
return 2;
}
else {
return 0;
}
}
void infixToPostfix(string st)
{
stack<char>op; //stack to hold operators and bracket
st += 'n';
int l = st.size();
op.push('0');
string fst; //final string
for(int x = 0;x<l;x++)
{
if(st[x] == '(')
{
op.push(st[x]);
}
else if(st[x] == ')')
{
while(op.top() != '(' && !op.empty())
{
fst +=op.top();
op.pop();
}
op.pop();
}
else if(st[x] == '+' || st[x] == '-' || st[x] == '*' ||st[x] == '/' ||st[x] == '^')
{
if(pr(st[x]) <= pr(op.top()))
{
fst += op.top();
op.pop();
op.push(st[x]);
}
else{
op.push(st[x]);
}
}
else if(st[x] == 'n'){
while(op.size() != 0)
{
if(op.top() != '0')
{fst += op.top();}
op.pop();
}
}
else if((st[x] >= 'a' || st[x] <= 'z' )&& st[x] != ' ')
{
fst += st[x];
}
}
printf("%s\n",fst.c_str());
}

undefined reference to `readVector(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'

I got this error message when I tried to compile my code:
c++ -Ofast -march=native -DNDEBUG -std=c++11 -Wc++11-extensions -Wall matvec.o amath483.o Vector.o -o matvec
matvec.o: In function main': matvec.cpp:(.text+0x209): undefined reference toreadVector(std::__cxx11::basic_string, std::allocator >)' clang: error: linker command failed with exit code 1 (use -v to see invocation) makefile:5: recipe for target 'matvec' failed make: *** [matvec] Error 1
My code is as follows:
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <fstream>
#include "Vector.hpp"
using namespace std;
Vector readVector(istream& input) {
string string_input;
int n;
getline(input,string_input);
if(string_input.compare("AMATH 583 VECTOR") != 0) exit(-1);
input >> n;
Vector v(n);
for(int i = 0; i < n; i++)
input >> v(i);
getline(input,string_input);
getline(input,string_input);
if(string_input.compare("THIS IS THE END") != 0) exit(-1);
return v;
}
Vector readVector(ifstream& file) {
string string_input;
int n;
getline(file,string_input);
if(string_input.compare("AMATH 583 VECTOR") != 0) exit(-1);
file >> n;
Vector v(n);
for(int i = 0; i < n; i++)
file >> v(i);
getline(file,string_input);
getline(file,string_input);
if(string_input.compare("THIS IS THE END") != 0) exit(-1);
return v;
}
#include "Vector.hpp"
#include <iostream>
#include <fstream>
#include "amath483.hpp"
using namespace std;
int main(int argc, char* argv[]) {
if(argc < 2 || argc > 4) {
cout << "You must provide at least one argument or at most three arguments(including two options)" << endl;
return -1;
}
int inputoption = -1;
int outputoption = -1;
if(argc == 3) {
inputoption = 0;
}
if(argc == 4) {
inputoption = 0;
outputoption = 0;
}
// Check the format
Vector v = NULL;
if(inputoption == 0) {
string inputfile = argv[2];
v = readVector(inputfile);
} else {
v = readVector(cin);
}
for(int i=0; i < v.numRows(); i++)
cout << v(i) << endl;
return 0;
}
Clearly you have wrong input type: std::string inputfile is not std::ifstream or std::istream. You need to open an input std::ifstream file, whose name stored in inputfile and then pass it to readVector.