Segmentation fault (core dumped) C++ Object Oriented Programming - c++

I'm a student of system engineering, 2nd semester of the ULA (Universidad de los Andes)
So, I'm programming a c++ mini project for university. The project consists of making a draft of a software oriented to buying and selling crypto currencies, however, since yesterday I've been getting a problem with it (a segmentation fault core dumped specifically)... So, as this page had been helpful with my previous programs and this time I didn't find something that could have helped me, I decided to register and ask in case someone is willing to help me.
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class usuario {
private :
string username[10], password[10];
int aux;
public :
usuario();
void setUnamep(string, string, int);
string getUnamep();
void setPass(string);
string getPass();
int DataAcc(string, string);
~usuario();
};
class moneda {
protected :
float cantidad;
public :
moneda(float);
void setCant(float);
void getCant();
~moneda();
};
class bitcoin : public moneda {
private :
float btc[20];
public :
bitcoin (float);
void setBuy(float, float[]);
void getBuy();
void mostrarc(float);
~bitcoin();
};
usuario::usuario () {
}
void usuario::setUnamep(string username_, string password_, int aux_) {
string PreUser[20], aux_2;
aux = aux_;
for (int i= 1; i <= aux; i++) {
username[i] = username_[i];
password[i] = password_[i];
cout<<"\nEnter an username: ";
cin>>username[i];
cout<<"Enter a password: ";
cin>>password[i];
username[0] = "."; //pass 1 leer
for (int v = 0 ; v < i; v++) {
if (username[v] == username[i]) {
cout<<"\nUsername already in use. Choose another"<<endl;
username[i] = "null";
password[i] = "null";
i--;
v = 20000;
}
}
}
}
int usuario::DataAcc(string InUs, string InPass) {
bool ing = false, ret = false;
int u = 0;
do {
if (InUs==username[u] and InPass==password[u]) {
ing = true;
u = 10;
ret = true;
}
else //////
u++;
}
while (ing == false and u<5);
if (u == 5)
cout<<"\nIncorrect user or password. Try again."<<endl;
if (ing == true) {
cout<<"\nAccount data..."<<endl;
}
return ret;
}
usuario::~usuario() {
}
moneda::moneda(float cantidad_) {
cantidad = cantidad_;
}
moneda::~moneda() {
}
bitcoin::bitcoin(float cantidad_) : moneda(cantidad_) {
}
void bitcoin::setBuy(float cantidad_, float btc_[]) {
int aux;
for (int i = 0; i < 20 ; i++) {
btc[i] = btc_[i];
}
cout<<"How many BTC do you wish to buy?: ";
cin>>cantidad;
btc[aux] = btc[aux] + cantidad;
}
bitcoin::~bitcoin() {
}
int main() {
int opc = 0, aux1;
string InUs, InPass;
int aux2 = 0;
bitcoin b1(0);
cout<<"Welcome to BitZuela 2018, down there you have several options for you to choice which one do you want to run. ";
cout<<"\n\n1. Sign Up."<<endl;
cout<<"2. Log in."<<endl;
cout<<"3. Finish program."<<endl;
usuario u1;
while (opc >=0 and opc <=2) {
cout<<"\nPress the button of the option you want to run: ";
cin>>opc;
if (opc==1) {
cout<<"\nHow many accounts do you want to register?: ";
cin>>aux1;
u1.setUnamep("null", "null", aux1);
}
if (opc==2) {
cout<<"\nUsername: ";
cin>>InUs;
cout<<"Password: ";
cin>>InPass;
aux2 = u1.DataAcc(InUs, InPass);
if (aux2 == 1) {
b1.setBuy(0,0); //The problem is when this object is created
}
}
if (opc == 3)
cout<<"\nProgram finished."<<endl;
}
return 0;
}
That's it, I would be very grateful if someone can help me solving this problem. Also, if you have a suggestion about another thing, It'll be a pleasure to read it!

There seems to be some trouble with this method
void bitcoin::setBuy(float cantidad_, float btc_[]) {
int aux;
for (int i = 0; i < 20 ; i++) {
btc[i] = btc_[i];
}
cout<<"How many BTC do you wish to buy?: ";
cin>>cantidad;
btc[aux] = btc[aux] + cantidad;
}
The 'aux' variable is used before it is set resulting in undefined behavior.
Also the call is passing a 0 instead of a float[]. The compiler interprets the 0 as a nullptr, resulting a crash in ::setBuy
if (aux2 == 1) {
b1.setBuy(0,0);
Probably some other issues but fixing these will be a step in the right direction

Your core dumped is in the setBuy function. You ask for an array of float, but when you call it in your code, you pass a "0", but you should pass an array of 20 elements.
The aux variable is set inside the function, but I think you should pass it from the signature of the function.
Also, the cantidad variable that you are using inside that function is not the one in the signature (you should remove it from the signature, or add an _ to cantidad).
I also looked into your setUnamep function, you should use an std::map for your username and password management (You can search for an already existing keys in log(n)).

Related

How do you compare and sort a specific parameter within a class?

My professor has asked us to make a program that will take a user's input and continue reading until the end of input. Only then, can the program output what the user has typed.
Input should be based on video title, it's url, comments made on the video, length (in minutes), and rating (in *).
For example:
United Break Guitars, https://www.youtube.com/watch?v+5YGc4zOqozo, Great example of one person getting a giant company to listen, 4.5, ***, Space Versus Tabs, https://www.youtube.com/watch?v=SsoOG6ZeyUl, Decide for yourself: spaces or tabs?, 2.83, ****
Up until what is explained, I have completed and tested to see if everything works. My problem is the next part of the project which requires the user to choose between Rating, Length, or title then sort them based on what the user chose.
If I chose Rating, then the input above should be sorted from highest rated video to lowest.
This is what I have so far:
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
using namespace std;
#include "video.h"
int main()
{
string user, url, comment, title;
int rating;
double length;
int i = 0, last = 0;
Video *videoObj[100];
Video *temp[100];
// specifies how the videos should be sorted
cin >> user;
cin.ignore();
while (getline(cin,title) ) {
getline(cin, url);
getline(cin, comment);
cin >> length;
cin >> rating;
cin.ignore();
videoObj[i] = new Video(title, url, comment, length, rating);
i++;
last++;
}
temp[i] = new Video(title, url, comment, length, rating);
if(user=="rating"){
for(int i = 0; i < last - 1; i++){
for(int j = i+1; j< last; j++){
if(videoObj[i] -> Rating(videoObj[j])) {
temp[i] = videoObj[i];
videoObj[i]= Rating(videoObj[j]);
Rating(videoObj[j]) = temp[i];
}
}
}
}
for(int i= 0; i < last; i++)
{
videoObj[i]->print();
}
//delete[] videoObj;
return 0;
}
video.cpp file:
#include <iostream>
#include <algorithm>
using namespace std;
#include "video.h"
Video::Video(string video_title, string video_link, string video_comment, double video_length, int video_number)
: title(video_title), link(video_link), comment(video_comment), length(video_length), rating(video_number)
{
}
bool Video::Rating(Video *videoObj) {
if(rating > videoObj-> rating )
{
return true;
}
else
{
return false;
}
}
void Video::print(){
string star;
switch(rating){
case 1:
star = "*";
break;
case 2:
star = "**";
break;
case 3:
star = "***";
break;
case 4:
star = "****";
break;
case 5:
star = "*****";
break;
}
cout << title << ", " << link << ", " << comment << ", " << length << ", " << star << endl;
}
void Video::temp(){
title, link, comment, length, rating;
}
video.h file:
#ifndef VIDEO_H
#define VIDEO_H
using namespace std;
class Video {
public:
Video(string video_title, string video_link, string video_comment, double video_length, int video_number);
void print();
bool Rating(Video *videoObj);
void temp();
private:
string title;
string link;
string comment;
double length;
int rating;
};
#endif
I honestly have no idea how to implement the bubble sort correctly. I have looked up multiple different videos on youtube and posts on stackoverflow, but I can't seem to figure out how to sort a specific parameter within my class.
My professor gave us these instructions for sorting within our class:
When sorting the videos you need to be able to determine how two video objects should be
ordered. The easiest way to do this is to write member functions to handle the comparisons in
class Video. For example, this method could be used when sorting the videos by length:
// return true if the current video is longer than the given video (other) ,
// otherwise return false
bool Video :: longer(Video *other) {
return (mlength > other -> mlength ;
}
I'm not even sure if I did that part correctly in my video.cpp file. Any ideas on how I can get the sorting method to work properly?
Please be gentle, I'm very new to programming. I realize my bubble sort is wrong as well, I just don't know where to start fixing it...
I'd normally use std::sort with a comparison operator for each field you want to be able to compare. You can implement those either as named classes:
struct by_title {
bool operator()(Video const &a, Video const &b) {
return a.title < b.title;
}
};
struct by_rating {
bool operator()(Video const &a, Video const &b) {
return a.rating < b.rating;
}
};
// ...
std::sort(videos.begin(), videos.end(), by_rating);
std::sort(videos.begin(), videos.end(), by_title);
...or you can use a lambda expression to define a comparison:
// sort by rating
std::sort(videos.begin(), videos.end(), [](auto &a, auto &b) { return a.rating < b.rating; });
// sort by title
std::sort(videos.begin(), videos.end(), [](auto &a, auto &b) { return a.title < b.title; });

Why "result" value is always equal to zero?

I'm going through a MOOC about an introduction to c++, and am stuck in an exercise about functions. The exercise is about a program that changes a number to the way it was read.
For example:
"1" is read like "one one" so the next number should be
"11" which is read like "two ones" the next number is
"21" -> "one two and one one"
"1211" -> "one one and one two and two ones"
"111221" -> "three ones and two twos and one one "
"312211"..... and so on
The user should give the starting number and the number of times we should do this operation, and the program should output the last number. Like in the example the input should be "1 5" and the program should print "312211". In the program they just asked to write three functions to complete the code they gave us.
void ajouter_chiffre_droit(int& nombre, int chiffre);
void dire_chiffre(int& nombre, int repetitions_chiffre, int chiffre);
int lire_et_dire(int nombre);
The part of the program they gave us is this and we should fill the three functions above:
#include <iostream>
using namespace std;
int separer_chiffre_gauche(int& nombre)
{
int dix(1);
int temp(nombre);
while (temp >= 10) {
dix *= 10;
temp /= 10;
}
nombre %= dix;
return temp;
}
/*****************************************************
* Compléter le code à partir d'ici
*****************************************************/
void ajouter_chiffre_droit(int& nombre, int chiffre)
{
}
void dire_chiffre(int& nombre, int repetitions_chiffre, int chiffre)
{
}
int lire_et_dire(int nombre)
{
}
/*******************************************
* Ne rien modifier après cette ligne.
*******************************************/
void repeter_lire_et_dire(int& nombre, int fois)
{
while (fois-- > 0) {
nombre = lire_et_dire(nombre);
}
}
int main()
{
int nombre(1);
int fois(1);
cin >> nombre >> fois;
repeter_lire_et_dire(nombre, fois);
cout << nombre << endl;
return 0;
}
My solution:
void ajouter_chiffre_droit(int& nombre, int chiffre)
{
nombre *= 10 + chiffre;
}
void dire_chiffre(int& nombre, int repetitions_chiffre, int chiffre)
{
ajouter_chiffre_droit(nombre, repetitions_chiffre);
ajouter_chiffre_droit(nombre, chiffre);
}
int lire_et_dire(int nombre)
{
int nombre_temp(nombre), chiffre(0), chiffre_prec(0), rep(1), resultat(0);
chiffre_prec = separer_chiffre_gauche(nombre_temp);
do
{
chiffre = separer_chiffre_gauche(nombre_temp);
if(chiffre == chiffre_prec)
{
++rep;
}
else
{
dire_chiffre(resultat, rep, chiffre_prec);
rep = 1;
chiffre_prec=chiffre;
}
}while(nombre_temp!=0);
return resultat;
}
The function lire_et_dire always returns the value 0 and i don't know why if you could please help me that will be great, thanks!
If you didn't understand the problem from me "probably", please read the official problem text here it's exercise number 1.

Segmentation fault error with structures

I have no idea where the segmentation error is coming from ... Any ideas?
I am working with structures for an assignment
TestResult testResultFactory(std::string name, double mark)
{
//creating an object of TestResult
TestResult car;
car.name = name;
car.mark = mark;
return car;
}
Student studentFactrory(std::string name)
{
//Creating an object of student
Student house;
house.name = name;
house.testResults = 0;
house.numTestResults = 0;
return house;
}
void addTestResult(Student * student, std::string testName, double testMark)
{
//First we need to create a new array
(student->numTestResults)+=1;
TestResult *newTestArray = new TestResult[(student->numTestResults)];
//Now we loop through the old array and add it to the new one
int index = (student->numTestResults);
for (size_t i = 0; i < (index-1); i++)
{
newTestArray[i] = testResultFactory((student->testResults[i].name),(student->testResults[i].mark));
}
//Now we need to add the new student to the end of the array
newTestArray[index] = testResultFactory(testName, testMark);
(student->testResults) = newTestArray;
}
string studentBest(Student const * student)
{
//create variables as temps
string highestName;
double highestMark;
int index = (student->numTestResults);
//Setting the two variables to the first value
highestName = (student->testResults[0].name);
highestMark = (student->testResults[0].mark);
//Using a while loop to compare and get the best
for (size_t i = 0; i < index; i++)
{
if((student->testResults[i].mark)> highestMark)
{
highestMark = (student->testResults[i].mark);
highestName = (student->testResults[i].name);
}
}
//returning the string they want
string send = (highestName)+ " "+ doubleToString(highestMark)+ "%";
return send;
}
double studentAverage(Student const * student)
{
//Variables used as temps
double average = 0;
double counter = 0.0;
double running = 0;
int index = (student->numTestResults);
//Now we need to loop through each one and add to running and counter
for (size_t i = 0; i < index; i++)
{
counter++;
running += (student->testResults[i].mark);
}
//calculating the average;
average = (running)/counter;
return average;
}
void destroyStudent(Student * student)
{
delete [] (student->testResults);
(student->testResults)=0;
}
Subject subjectFactory(std::string name)
{
//Creating an object to use in subject factory
Subject lamp;
lamp.name = name;
lamp.numStudents = 0;
lamp.studentsAllocated = 0;
lamp.students = 0;
return lamp;
}
MY guess is that the error occurs because of an out of bounds array or an pointer not worked with correctly .
int getStudentIndex(Subject const * subject, std::string studentName)
{
int index;
int count = (subject->numStudents);
//loop to find the names and set index
for (size_t i = 0; i < count; i++)
{
if(studentName == ((subject->students[i].name)))
{
index = i;
}
else index = -1;
}
return index;
}
void addStudent(Subject * subject, std::string studentName)
{
//Variables as temps
Student *pointer =0;
int index = getStudentIndex(subject,studentName);
if(index != -1)
{
//Now we need to see if they are large enough
if((subject->studentsAllocated)==0)
{
//Set the allocated to 2
(subject->studentsAllocated) = 2;
pointer = new Student[2];
//Figure this out later
pointer[1] = studentFactrory(studentName);
(subject->students) = pointer;
}
else
{
//increase SA with 1.5
(subject->studentsAllocated) = (subject->studentsAllocated) * 1.5;
pointer = new Student[(subject->studentsAllocated)+1];
int count = (subject->studentsAllocated);
//Now we need to put all the other students in
for (size_t i = 0; i < count-1; i++)
{
pointer[i] = (subject->students[i]);
}
pointer[(subject->studentsAllocated)+1] = studentFactrory(studentName);
(subject->studentsAllocated) += 1 ;
}
//Once done just seet one equal to
(subject->students) = pointer;
}
else return;
}
void removeStudent(Subject * subject, std::string studentName)
{
//First get temps
int index = getStudentIndex(subject ,studentName);
int number = (subject->studentsAllocated);
int i = index;
//delete student
if(index == -1) return;
destroyStudent(&(subject->students)[index]);
//loop to shift the things
while (i<(number -1))
{
(subject->students)[i] = (subject-> students[i+1]);
}
//Removing the last one
(subject->numStudents) -= 1;
}
bool addTestResult(Subject * subject, std::string studentName, std::string testName, double testMark)
{
int index = getStudentIndex(subject ,studentName);
if(index != -1)
{
addTestResult(&(subject->students [index]),testName,testMark);
return true;
}
else
return false;
}
void printSubjectSummary(Subject const * subject)
{
cout<<(subject->name)<< ": with "<<(subject->numStudents)<<" students"<<endl;
//Variables to use in the loop
size_t indexLoop = subject->numStudents;
int i=0;
while (i< indexLoop)
{
cout<<(subject->students[i].name)<<" Average: "<<studentAverage(&(subject->students[i]))<<", Best: "<<studentBest(&(subject->students[i]))<<endl;
}
}
void destroySubject(Subject * subject)
{
//Variables
size_t indexLoop = subject->numStudents;
for (size_t i = 0; i < indexLoop; i++)
{
destroyStudent(&(subject->students[i]));
}
delete [] subject->students;
subject->students =0;
}
I can not seem to find where the segmentation error is coming from. Even restarted the whole assignment from scratch and still seem to get errors.
Can someone please help or indicate where the fault could be coming from.
Over here we have the structs.h file that is included in my code above
#ifndef STRUCTS_H
#define STRUCTS_H
struct TestResult{
double mark;//the test mark as a percentage
std::string name;//the test name
};
struct Student{
std::string name;
TestResult * testResults;//an arry of TestResults
size_t numTestResults;//the number of results for this student (also the size of the array)
};
struct Subject{
std::string name;
Student * students;//an array of Students
size_t numStudents;//the number of students added to the subject
size_t studentsAllocated;//the size of the Student arry(must never be smaller that numStudents)
};
#endif
There are so many logical errors in there that the root cause (or causes; there are quite a few candidates) could be pretty much anywhere.
getStudentIndex returns -1 unless the student is the last one in the array, and an indeterminate value for the first one you add, so adding the first student to a subject is undefined.
addStudent only adds a student if they're already taking the subject.
It also (for some inexplicable reason) allocates an array of two Students, leaving the first element uninitialised.
Using this first element is, of course, undefined.
In the other branch, it first claims that the number of allocated students is * 1.5, but then only allocates + 1.
This will undoubtedly lead to problems.
There is a recursion in addTestResult that will never terminate.
There are most likely other problems as well – this was just a quick glance.
Start with fixing these.
And do learn about constructors and destructors so you can get rid of those "factory" and "destroy" functions.

std::bad_alloc at memory location 0x002b123c

I am making a small program. First I made a Header File:
private:
string UserName, Password;
public:
void setUN(string);
void setP(string);
string getUN();
Then in my cpp file:
void UserInfo::setUN(string un){
UserName = un;
}
string UserInfo::getUN(){
return UserName;
}
After that in my main I make a object:
UserInfo addUser[100];
to add users
cout<<"Enter Username : ";
getline(cin,tUN);
addUser[0].setUN(tUN);
After that in my other function void LoginScreen()
I made the same object:
UserInfo addUser[100];
string EUN, EP;
system("cls");
cout<<"Enter Username : ";
cin>>EUN;
cout<<endl;
cout<<"Enter Password : ";
//cin>>EP;
for( int a = 0; a <= 100; a++){
if (EUN == addUser[a].getUN()){
system("cls");
cout<<"OMG HELP MEEE ";
break;
}
}
It works fine when till get to this for loop and gives this error:
std::bad_alloc at memory location 0x002b123c
Can you tell me what the error means and how can I get rid of this.
UserInfo addUser[100]; has elements indexed from 0 - 99.
So fix:-
for( int a = 0; a <= 100; a++){
^^This should be a < 100
}

Stack-based palindrome checker

i have a problem with my program. It should be program that recognize palindome through the stack. Everything works great, only thing that don't work is printing stacks(original and reversed) after the funcion is done.
Here is my entire code, and the problem is at case d and e:
#include <iostream>
using namespace std;
const int MAXSTACK = 21;
class stack {
private:
int stop;
char stk[MAXSTACK];
public:
stack();
~stack();
stack(const stack& s);
void push(const char c);
char pop();
char top(void);
int emptystack(void);
int fullstack(void);
void stack_print(void);
int stack::create(void);
};
stack::stack()
{
stop = 0;
}
stack::~stack() { }
stack::stack(const stack& s)
{
stop = s.stop;
strcpy(stk,s.stk);
}
void stack::push(const char c)
{
stk[stop++] = c;
}
char stack::pop()
{
return stop--;
}
char stack::top(void)
{
return stk[stop - 1];
}
int stack::emptystack(void)
{
return !stop;
}
int stack::fullstack(void)
{
return stop == MAXSTACK;
}
void stack::stack_print(void)
{
for (int i=0; i<stop; i++)
cout<<stk[i];
cout<<endl;
}
int stack::create(void)
{
return !stop;
}
char menu()
{
char volba;
cout<<"\n";
cout<<" **********.\n";
cout<<"\n";
cout<<" a ... make new containers\n";
cout<<" b ... delete content\n";
cout<<" c ... enter string\n";
cout<<" d ... print on screen first stack\n";
cout<<" e ... print on screen first stack\n";
cout<<" f ... is it palindrom\n";
cout<<" x ... exit\n";
cout<<"\n your choice : ";
cin >> volba;
return volba;
}
int main() {
char palindrome[MAXSTACK];
char volba;
stack original,reversed;
int stackitems = 0,i;
//cin.getline(palindrome,MAXSTACK);
do{
volba = menu();
switch (volba)
{
case'a':
{
original.create();
reversed.create();
cout<<"done'";
break;
}
case'b':
{
original.emptystack();
reversed.emptystack();
cout<<"empty";
break;
}
case'c':
{
cout<<"enter your string"<<endl;
cin.get();
//cin.get();
cin.getline(palindrome,MAXSTACK);
for(int o = 0; o < strlen(palindrome); o++)
if (isalpha(palindrome[o]))
{
original.push(tolower(palindrome[o]));
stackitems++;
}
original.stack_print();
break;
}
case'd':
{
original.~stack();
for(int g = 0; g < strlen(palindrome); g++)
original.push(tolower(palindrome[g]));
original.stack_print();
}
/*//cin.getline(palindrome,MAXSTACK);
for(int g = 0; g < strlen(palindrome); g++)
if (isalpha(palindrome[g]))
{
original.push(tolower(palindrome[g]));
stackitems++;
}
}
original.stack_print();*/
break;
/*{
cout<<"original: ";
original.stack_print();
break;
}*/
break;
case'e':
{
cout<<"reversed:"<<endl;
for( i = 0; i < stackitems; i++) {
reversed.push(original.top());
original.pop();
}
reversed.stack_print();
}
break;
case'f':
{
for( i = 0; i < stackitems / 2; i++) {
reversed.push(original.top());
original.pop();
}
if (stackitems % 2)
original.pop();
while (!original.emptystack()) {
if (original.top() != reversed.top()) break;
original.pop(); reversed.pop();
}
if (original.emptystack())
cout << "it is palindrom\n";
else
cout << "not palindrom\n";
break;
}
default:cout<<"!??!";
}
} while(volba!='x');
}
You've explicitly called your stack's destructor. There is almost never a good reason to do this. If the stack is a local ("on the stack", hee hee), the compile will do it for you. If it's on the heap, created with new, call delete on it, which will cause the compiler to call the destructor.
case'd':
{
original.~stack();
You have commented palindrome reading :)
//cin.getline(palindrome,MAXSTACK);
There are a few things I would like to respond with. First, I think GMan, tpdi, and Vinay all have good points. This FAQ explains why calling the destructor on a local variable is a bad idea.
I realize this is just a simple homework problem and you are probably just trying to keep your stack class lightweight, but you might consider using a container class instead of an array of characters in your stack class.
Next, I'm not sure your emptystack and create functions are doing what you think they are doing. When you declare your original and reversed stack classes in the main program the memory is allocated for your internal character array. It's not really necessary in this case to have a create function. Perhaps if you were allocating memory on the heap for your character array, you would put that code into the create function (if you chose to leave it out of the constructor for some reason), but that's not the case here.
Similarly, emptystack isn't really doing anything. It would be better to have empty stack set the stop member variable to 0. At least that way the stack would appear to be empty the next time someone tried to use it.
There's a lot more that could be said about this class, but it might be better if you tried some of the suggestions here like using the std::stack and debugging. This is, after all, your homework assignment: it will help you a lot more in the future if you find the solution yourself!