Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Could you please tell me where is the memory leak and explain why i did wrong? I can't find the problem and i don't find the answer on google.
#include <iostream>
using namespace std;
class Avion{
private:
static int autoincrementare;
char* nume;
int randuri;
int* locuri ;
const double pret = 100.00;
int nrPersonal;
bool servire;
public:
// setteri si getteri
int getRanduri(){
return this->randuri;
}
int getNrPersonal(){
return this->nrPersonal;
}
bool getServire(){
return this->servire;
}
char* getNume(){
return this->nume;
}
int* getLocuri(){
return this->locuri;
}
void setNume(char* nume){
if (nume != NULL) delete this->nume;
this->nume = new char[strlen(nume) + 1];
strcpy(this->nume, nume);
}
void setLocuri(int* locuri){
if (randuri != NULL) {
this->locuri = new int[this->randuri];
for (int i = 0; i < randuri; i++)
this->locuri[i] = locuri[i];
}
}
void setRanduri(int randuri){
this->randuri = randuri;
}
void setNrPersonal(int nrPersonal){
this->nrPersonal = nrPersonal;
}
void setServire(bool servire){
this->servire = servire;
}
//constructor fara parametrii
Avion() :pret(autoincrementare++){
this->randuri = 3;
this->servire = true;
this->nrPersonal = 10;
this->nume = new char[strlen("Luft") + 1];
strcpy(this->nume, "Luft");
this->locuri = new int[this->randuri];
for (int i = 0; i < this->randuri; i++){
this->locuri[0] = 30;
this->locuri[1] = 40;
this->locuri[2] = 50;
}
}
Avion(int randuri, bool servire, int nrPersonal, char* nume, int* locuri) :pret(autoincrementare++){
this->randuri = randuri;
this->servire = servire;
this->nrPersonal = nrPersonal;
//if (nume != NULL) delete this->nume;
this->nume = new char[strlen(nume) + 1];
strcpy(this->nume, nume);
// if (locuri != NULL)delete this->locuri;
this->locuri = new int(this->randuri);
for (int i = 0; i < randuri; i++)
{
this->locuri[i] = locuri[i];
}
}
friend ostream & operator<<(ostream & out, Avion & a){
out << "Avionul are " << a.randuri << " randuri" << endl;
out << "Avionul are deschis bufetul : " << a.servire << endl;
out << "Avionul are numarul de personal de: " << a.nrPersonal << endl;
out << "Avionul are numele : " << a.nume << endl;
out << " Avionul are: " << a.randuri << " randuri cu " << endl;
for (int i = 0; i < a.getRanduri(); i++){
cout << a.getLocuri()[i] << " locuri " << endl;
}
return out;
}
friend istream & operator >>(istream & in, Avion &a){
char aux[50];
cout << "Nume avion : "; in >> aux;
if (a.nume != NULL) delete[] a.nume;
a.nume = new char[strlen(aux) + 1];
strcpy(a.nume, aux);
return in;
}
Avion& operator=(const Avion& a){
this->randuri = a.randuri;
this->servire = a.servire;
this->nrPersonal = a.nrPersonal;
this->nume = new char[strlen(a.nume) + 1];
strcpy(this->nume, a.nume);
this->locuri = new int(this->randuri);
for (int i = 0; i < randuri; i++)
{
this->locuri[i] = a.locuri[i];
}
return *this;
}
~Avion(){
if (nume != NULL) delete[] this->nume;
if (locuri != NULL) delete[] this->locuri;
}
};
int Avion::autoincrementare = 1;
void main(){
Avion Luft;
cin >> Luft;
cout << Luft << endl;
cout << "================================"<<endl;
cout << "==========================" << endl;
int a[3]{10, 20, 30};
Avion BlueAir(3, true, 10, "Blue Air", a);
cout << BlueAir << endl;
/*
Avion G6;
G6 = Luft;
cout << G6 << endl;
cout << "==================";
cout << Luft << endl;
*/
}
In this code, the first line of the function is doing a delete instead of a delete[]. So that's at least one memory leak.
void setNume(char* nume){
if (nume != NULL) delete this->nume;
this->nume = new char[strlen(nume) + 1];
strcpy(this->nume, nume);
}
You have to match new with delete and new[] with delete[].
Related
I am trying to make a first fit memory management code but everytime I try to run it I keep getting incomplete results in the output and these errors
error:expected primary-expression before ‘,’ token
I don't know what to put in the code to resolve this error
#include"stdafx.h"
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<memory.h>
#include <cstdlib>
using namespace std;
struct allocList
{
char* startAlloc;
char* endAlloc;
int fk_pid;
allocList *nxt;
};
struct procList
{
int pid;
int jobstatus;
char *startProc;
char *endProc;
procList *nxt;
};
bool initProc(procList*&, int*, int);
bool initAlloc(allocList*&, int*, int);
int doFirstFit(procList*, allocList*);
int cmptFragmentation(procList*, allocList*);
int search(procList*, int);
bool reset(procList*, allocList*);
int main()
{
int arrMemory[] = { 100, 500, 200, 300, 600 };
int arrJobs[] = { 212, 17, 112, 426, 500 };
allocList *ptrAllocStart = NULL;
procList *ptrProcStart = NULL;
initAlloc(ptrAllocStart, arrMemory, (sizeof(arrMemory) / sizeof(int)));
initProc(ptrProcStart, arrJobs, (sizeof(arrJobs) / sizeof(int)));
cout << "Memory Block: " << endl << "Block\tSpace" << endl;
for (int i = 0; i < sizeof(arrMemory) / sizeof(int); i++)
{
cout << i + 1 << "\t" << arrMemory[i] << endl;
}
cout << "\nJobs:" << endl << "Job\tSize" << endl;
for (int i = 0; i < sizeof(arrJobs) / sizeof(int); i++)
{
cout << i + 1 << "\t" << arrJobs[i] << endl;
}
int jobLoaded = 0;
int fragmentation = 0;
jobLoaded = doFirstFit(ptrProcStart, ptrAllocStart);
fragmentation = cmptFragmentation(ptrProcStart, ptrAllocStart);
allocList* memtrav = ptrAllocStart;
getch();
return 0;
}
bool initProc(procList*& ptrProcStart, int* ptrArrProc, int length){
int i;
procList *ptrProc=ptrProcStart;
for(i=0; i<length; i++){
if(ptrProc != NULL){
ptrProc->nxt=new procList;
ptrProc = ptrProc->nxt; ptrProc->startProc=(char*)malloc(*(ptrArrProc+i));
ptrProc->endProc=ptrProc->startProc + *(ptrArrProc+i);
memset(ptrProc->startProc,'a'+i,*(ptrArrProc+i));
ptrProc->jobstatus=0;
ptrProc->pid=i;
ptrProc->nxt=NULL;
}
else
{
ptrProc=new procList;
ptrProc->startProc=(char*)malloc(*(ptrArrProc+i));
ptrProc->endProc=ptrProc->startProc + *(ptrArrProc+i);
memset(ptrProc->startProc, 'a'+i, *(ptrArrProc+i));
ptrProc->jobstatus=0;
ptrProc->pid=i;
ptrProc->nxt=NULL;
ptrProcStart = ptrProc;}}
return true; }
bool initAlloc(allocList*& ptrAllocstart, int* ptrArrAlloc, int length)
{
//cout << "loading function initAlloc"<< "\t" << length << endl;
int i;
allocList* ptrAlloc = ptrAllocstart;
for (i = 0; i < length; i++)
{
//cout << "running loop 1st"<< "\t" << i << endl;
if (ptrAlloc != NULL)
{
ptrAlloc -> nxt = new allocList;
ptrAlloc = ptrAlloc->nxt;
//cout << "after new ptrAlloc" << endl;
ptrAlloc->startAlloc=(char*)malloc(*(ptrArrAlloc+i));
ptrAlloc->endAlloc=ptrAlloc->startAlloc + *(ptrArrAlloc+i);
memset(ptrAlloc->startAlloc,'a'+i,*(ptrArrAlloc+i));
ptrAlloc->nxt=NULL;
}
else
{ //cout << "inside else"<< "\t" << i << endl;
ptrAlloc= new allocList;
ptrAlloc->startAlloc-(char*)malloc(*(ptrArrAlloc+i));
ptrAlloc->endAlloc-ptrAlloc->startAlloc + *(ptrArrAlloc+i);
memset(ptrAlloc->startAlloc, 'a'+i, *(ptrArrAlloc+i));
ptrAlloc->nxt=NULL;
ptrAllocstart=ptrAlloc;
}
}
return true;
}
int doFirstFit(procList*, allocList*){
//cout lang ng UI
cout << "\n\nFirst Fit:\nMemory Block\tSize\tJob\tInternal " << " Fragmentation\n" << endl;
//declaration ng variable
int i = 0;
allocList* memory;
//mag do while sa memory n walang laman?
while (memory != NULL)
i++;
cout << "\t" << i << "\t" << memory->endAlloc - memory->startAlloc << "\t"
<< memory->fk_pid << "\t"
//<< memory->endAlloc - memory->startAlloc - search(procList,memory->fk_pid - 1)
<< endl;
memory = memory->nxt;
return 0;
}
int search(procList* job, int id)
{
int size = 0;
while (job != NULL)
{
if (job->pid == id)
{
size =atoi(job->endProc) - atoi(job->startProc);
break;
}
job = job->nxt;
}
return size;
}
int cmptFragmentation(procList * jobs, allocList * mem)
{
allocList* memtrav, * temp;
procList* jobtrav;
jobtrav = jobs;
memtrav = mem;
int freespace = 0, memsize, jobsize;
int i = 0;
while (memtrav->nxt != NULL)
{
if (memtrav->nxt->fk_pid == 0)
{
freespace += (memtrav->nxt->endAlloc - memtrav->nxt->startAlloc);
temp = memtrav->nxt;
memtrav->nxt = memtrav->nxt->nxt; delete temp;
}
memtrav = memtrav->nxt;
}
if (memtrav->fk_pid == 0)
{
freespace += (memtrav->endAlloc - memtrav->startAlloc);
memtrav = memtrav->nxt;
}
memtrav = mem;
while (memtrav != NULL)
{
jobsize = search(jobs, memtrav->fk_pid - 1);
memsize = memtrav->endAlloc - memtrav->startAlloc;
if (memtrav->fk_pid != 0)
{
memtrav->endAlloc = memtrav->startAlloc + jobsize;
}
freespace += (memsize - jobsize);
memtrav = memtrav->nxt;
}
memtrav = mem;
while (memtrav != NULL)
{
if (memtrav->nxt == NULL)
{
memtrav->nxt = new allocList;
memtrav = memtrav->nxt;
memtrav->startAlloc = (char*)malloc(freespace);
memtrav->endAlloc = memtrav->startAlloc + freespace;
memset(memtrav->startAlloc, 0, freespace);
memtrav->fk_pid = 0;
memtrav->nxt = NULL;
break;
}
memtrav = memtrav->nxt;
}
memtrav = mem;
cout << endl << endl << "Defragmentation\nMemory " << "Block\tSize\tJob\tFreeSpace\n";
while (memtrav != NULL)
{
i++;
cout << "\t" << i << "\t" << memtrav->endAlloc - memtrav->startAlloc << "\t" << memtrav->fk_pid
<< "\t" << memtrav->endAlloc - memtrav->startAlloc - search(jobs, memtrav->fk_pid - 1) << endl;
memtrav = memtrav->nxt;
}
while (jobtrav != NULL)
{
if (jobtrav->jobstatus == 0)
{
doFirstFit(jobs, mem);
cmptFragmentation(jobs, mem);
}
jobtrav = jobtrav->nxt;
}
return 0;
}
bool reset(procList* jobs, allocList* mem)
{
procList* tempj = jobs;
allocList* tempa = mem;
while (jobs->nxt != NULL)
{
jobs = jobs->nxt;
free(tempj);
tempj = jobs;
}
free(tempj);
while (mem->nxt != NULL)
{
mem = mem->nxt;
free(tempa);
tempa = mem;
}
free(tempa);
return true;
}
This is the part where I commented where the error has an issue with and I don't know what I'm doing wrong
<< memory->endAlloc - memory->startAlloc - search(procList,memory->fk_pid - 1)
Please help, thank you so much!
In this function call
search(procList,memory->fk_pid - 1)
there is used the type specifier procList instead of an expression.
Pay attention to that such a function definition where its parameters are not used
int doFirstFit(procList*, allocList*){
//cout lang ng UI
cout << "\n\nFirst Fit:\nMemory Block\tSize\tJob\tInternal " << " Fragmentation\n" << endl;
//declaration ng variable
int i = 0;
allocList* memory;
//..
does not make a sense.
Moreover there is used uninitialized pointer
allocList* memory;
in expressions like for example this
memory = memory->nxt;
that invokes undefined behavior.
The function is called with arguments as
doFirstFit(jobs, mem);
So you need use the passed arguments within the function instead of declaring local variables like this
allocList* memory;
In the analysis I've done the error is this
memory->endAlloc - memory->startAlloc - search(procList,memory->fk_pid - 1)
otherwise direct passing of proclist, you must declare its pointer variable just like you did for Alloclist memory; by same way you'll resolve this
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<memory.h>
#include <cstdlib>
using namespace std;
struct allocList
{
char* startAlloc;
char* endAlloc;
int fk_pid;
allocList *nxt;
};
struct procList
{
int pid;
int jobstatus;
char *startProc;
char *endProc;
procList *nxt;
};
bool initProc(procList*&, int*, int);
bool initAlloc(allocList*&, int*, int);
int doFirstFit(procList*, allocList*);
int cmptFragmentation(procList*, allocList*);
int search(procList*, int);
bool reset(procList*, allocList*);
int main()
{
int arrMemory[] = { 100, 500, 200, 300, 600 };
int arrJobs[] = { 212, 17, 112, 426, 500 };
allocList *ptrAllocStart = NULL;
procList *ptrProcStart = NULL;
initAlloc(ptrAllocStart, arrMemory, (sizeof(arrMemory) / sizeof(int)));
initProc(ptrProcStart, arrJobs, (sizeof(arrJobs) / sizeof(int)));
cout << "Memory Block: " << endl << "Block\tSpace" << endl;
for (int i = 0; i < sizeof(arrMemory) / sizeof(int); i++)
{
cout << i + 1 << "\t" << arrMemory[i] << endl;
}
cout << "\nJobs:" << endl << "Job\tSize" << endl;
for (int i = 0; i < sizeof(arrJobs) / sizeof(int); i++)
{
cout << i + 1 << "\t" << arrJobs[i] << endl;
}
int jobLoaded = 0;
int fragmentation = 0;
jobLoaded = doFirstFit(ptrProcStart, ptrAllocStart);
fragmentation = cmptFragmentation(ptrProcStart, ptrAllocStart);
allocList* memtrav = ptrAllocStart;
getch();
return 0;
}
bool initProc(procList*& ptrProcStart, int* ptrArrProc, int length){
int i;
procList *ptrProc=ptrProcStart;
for(i=0; i<length; i++){
if(ptrProc != NULL){
ptrProc->nxt=new procList;
ptrProc = ptrProc->nxt; ptrProc->startProc=(char*)malloc(*(ptrArrProc+i));
ptrProc->endProc=ptrProc->startProc + *(ptrArrProc+i);
memset(ptrProc->startProc,'a'+i,*(ptrArrProc+i));
ptrProc->jobstatus=0;
ptrProc->pid=i;
ptrProc->nxt=NULL;
}
else
{
ptrProc=new procList;
ptrProc->startProc=(char*)malloc(*(ptrArrProc+i));
ptrProc->endProc=ptrProc->startProc + *(ptrArrProc+i);
memset(ptrProc->startProc, 'a'+i, *(ptrArrProc+i));
ptrProc->jobstatus=0;
ptrProc->pid=i;
ptrProc->nxt=NULL;
ptrProcStart = ptrProc;}}
return true; }
bool initAlloc(allocList*& ptrAllocstart, int* ptrArrAlloc, int length)
{
//cout << "loading function initAlloc"<< "\t" << length << endl;
int i;
allocList* ptrAlloc = ptrAllocstart;
for (i = 0; i < length; i++)
{
//cout << "running loop 1st"<< "\t" << i << endl;
if (ptrAlloc != NULL)
{
ptrAlloc -> nxt = new allocList;
ptrAlloc = ptrAlloc->nxt;
//cout << "after new ptrAlloc" << endl;
ptrAlloc->startAlloc=(char*)malloc(*(ptrArrAlloc+i));
ptrAlloc->endAlloc=ptrAlloc->startAlloc + *(ptrArrAlloc+i);
memset(ptrAlloc->startAlloc,'a'+i,*(ptrArrAlloc+i));
ptrAlloc->nxt=NULL;
}
else
{ //cout << "inside else"<< "\t" << i << endl;
ptrAlloc= new allocList;
ptrAlloc->startAlloc-(char*)malloc(*(ptrArrAlloc+i));
ptrAlloc->endAlloc-ptrAlloc->startAlloc + *(ptrArrAlloc+i);
memset(ptrAlloc->startAlloc, 'a'+i, *(ptrArrAlloc+i));
ptrAlloc->nxt=NULL;
ptrAllocstart=ptrAlloc;
}
}
return true;
}
int doFirstFit(procList*, allocList*){
//cout lang ng UI
cout << "\n\nFirst Fit:\nMemory Block\tSize\tJob\tInternal " << " Fragmentation\n" << endl;
//declaration ng variable
int i = 0;
allocList* memory;
procList*ab;
//mag do while sa memory n walang laman?
while (memory != NULL)
i++;
int mem=memory->fk_pid - 1;
cout << "\t" << i << "\t" << memory->endAlloc - memory->startAlloc << "\t"<< memory->fk_pid << "\t"<< memory->endAlloc - memory->startAlloc - search(ab,mem)<< endl;
memory = memory->nxt;
return 0;
}
int search(procList* job, int id)
{
int size = 0;
while (job != NULL)
{
if (job->pid == id)
{
size =atoi(job->endProc) - atoi(job->startProc);
break;
}
job = job->nxt;
}
return size;
}
int cmptFragmentation(procList * jobs, allocList * mem)
{
allocList* memtrav, * temp;
procList* jobtrav;
jobtrav = jobs;
memtrav = mem;
int freespace = 0, memsize, jobsize;
int i = 0;
while (memtrav->nxt != NULL)
{
if (memtrav->nxt->fk_pid == 0)
{
freespace += (memtrav->nxt->endAlloc - memtrav->nxt->startAlloc);
temp = memtrav->nxt;
memtrav->nxt = memtrav->nxt->nxt; delete temp;
}
memtrav = memtrav->nxt;
}
if (memtrav->fk_pid == 0)
{
freespace += (memtrav->endAlloc - memtrav->startAlloc);
memtrav = memtrav->nxt;
}
memtrav = mem;
while (memtrav != NULL)
{
jobsize = search(jobs, memtrav->fk_pid - 1);
memsize = memtrav->endAlloc - memtrav->startAlloc;
if (memtrav->fk_pid != 0)
{
memtrav->endAlloc = memtrav->startAlloc + jobsize;
}
freespace += (memsize - jobsize);
memtrav = memtrav->nxt;
}
memtrav = mem;
while (memtrav != NULL)
{
if (memtrav->nxt == NULL)
{
memtrav->nxt = new allocList;
memtrav = memtrav->nxt;
memtrav->startAlloc = (char*)malloc(freespace);
memtrav->endAlloc = memtrav->startAlloc + freespace;
memset(memtrav->startAlloc, 0, freespace);
memtrav->fk_pid = 0;
memtrav->nxt = NULL;
break;
}
memtrav = memtrav->nxt;
}
memtrav = mem;
cout << endl << endl << "Defragmentation\nMemory " << "Block\tSize\tJob\tFreeSpace\n";
while (memtrav != NULL)
{
i++;
cout << "\t" << i << "\t" << memtrav->endAlloc - memtrav->startAlloc << "\t" << memtrav->fk_pid
<< "\t" << memtrav->endAlloc - memtrav->startAlloc - search(jobs, memtrav->fk_pid - 1) << endl;
memtrav = memtrav->nxt;
}
while (jobtrav != NULL)
{
if (jobtrav->jobstatus == 0)
{
doFirstFit(jobs, mem);
cmptFragmentation(jobs, mem);
}
jobtrav = jobtrav->nxt;
}
return 0;
}
bool reset(procList* jobs, allocList* mem)
{
procList* tempj = jobs;
allocList* tempa = mem;
while (jobs->nxt != NULL)
{
jobs = jobs->nxt;
free(tempj);
tempj = jobs;
}
free(tempj);
while (mem->nxt != NULL)
{
mem = mem->nxt;
free(tempa);
tempa = mem;
}
free(tempa);
return true;
}
The above working just fine.
I am creating a dynamic array class that holds polynomials. The problem I am having right now is when I run my code, once it hits the return statement in main it begins to call the destructor and begins to free the memory from each instance starting with C. It deletes C fine, but when it gets to B I get a heap corruption error. I have tried walking through the code, but I cannot see where the corruption is happening. Can anyone help me? The exact error it gives me is "CRT detected that the application wrote to memory after end of heap buffer."
*Edit: I am more than happy to get peoples recommendations to help make my code better, but remember this is for a class and has specific rules. I cannot use anything from STL. I love any criticism you can give me.
///////////////////////////Header/////////////////////////////
class Poly
{
friend std::ostream& operator<<(std::ostream& output, const Poly& pNomial);
public:
Poly();
Poly(const int& coeff, const int& degree = 0);
Poly(const Poly& copy);
~Poly();
void setCoeff(const int& coeff, const int& degree);
bool isEmpty()const;
Poly& operator=(const Poly& pNomial);
private:
int* coeffs;
int highestDegree;
};
///////////////////////////CPP////////////////////////
#include "poly.h"
Poly::Poly()
{
highestDegree = 0;
coeffs = new int[highestDegree+1]();
}
Poly::Poly(const int & coeff, const int & degree)
{
if (degree >= 0)
{
highestDegree = degree;
coeffs = new int[highestDegree + 1]();
coeffs[degree] = coeff;
}
else
{
highestDegree = 0;
coeffs = new int[highestDegree + 1]();
}
}
Poly::Poly(const Poly& copy)
{
highestDegree = copy.highestDegree;
coeffs = new int[highestDegree + 1]();
for (int i = 0; i < copy.highestDegree + 1; i++)
{
coeffs[i] = copy.coeffs[i];
}
}
Poly::~Poly()
{
delete[] coeffs;
}
void Poly::setCoeff(const int& coeff, const int& degree)
{
if (degree > this->highestDegree)
{
Poly temp = *this;
delete[] this->coeffs;
this->highestDegree = degree;
this->coeffs = new int[highestDegree]();
for (int i = 0; i < temp.highestDegree + 1; i++)
{
this->coeffs[i] = temp.coeffs[i];
}
}
if (degree >= 0)
{
this->coeffs[degree] = coeff;
}
}
bool Poly::isEmpty()const
{
bool check = true;
for (int i = 0; i < highestDegree + 1 && check; i++)
{
if (coeffs[i] != 0)
{
check = false;
}
}
return check;
}
Poly & Poly::operator=(const Poly& pNomial)
{
if (this != &pNomial)
{
delete[] this->coeffs;
this->highestDegree = pNomial.highestDegree;
this->coeffs = new int[this->highestDegree + 1]();
for (int i = 0; i < pNomial.highestDegree + 1; i++)
{
this->coeffs[i] = pNomial.coeffs[i];
}
}
return *this;
}
std::ostream& operator<<(std::ostream& output, const Poly& poly)
{
if (!poly.isEmpty())
{
for (int i = poly.highestDegree; i >= 0; i--)
{
if (i == 1 && poly.coeffs[i] != 0)
{
if (poly.coeffs[i] >= 1)
{
output << " +" << poly.coeffs[i] << "x";
}
else
{
output << " " << poly.coeffs[i] << "x";
}
}
else if (i == 0 && poly.coeffs[i] != 0)
{
if (poly.coeffs[i] >= 1)
{
output << " +" << poly.coeffs[i];
}
else
{
output << " " << poly.coeffs[i];
}
}
else if (poly.coeffs[i] != 0)
{
if (poly.coeffs[i] >= 1)
{
output << " +" << poly.coeffs[i] << "x^" << i;
}
else
{
output << " " << poly.coeffs[i] << "x^" << i;
}
}
}
}
else
{
output << " 0";
}
return output;
}``
/////////////////////////////////Main/////////////////////////
#include "poly.h"
#include <iostream>
int main()
{
Poly A, B(5, 7), C(2);
B.setCoeff(2, 10);
B.setCoeff(1, 3);
B.setCoeff(5, 4);
std::cout << A << std::endl;
std::cout << B << std::endl;
std::cout << C << std::endl;
return 0;
}
I must say, that I agree with comments and you should seriously look into proper lifetime management of resources you use in the Poly class.
To answer the problem you're facing now have a look at the setCoeff() function.
this->coeffs = new int[highestDegree]();
should be changed to,
this->coeffs = new int[highestDegree + 1]();
With your current implementation, you allocate the array with highestDegree and in your for loop you access temp.coeffs[highestDegree] which is out of bounds access i.e. you loop till i < temp.highestDegree + 1.
I was given an exercise on overloading operators by my tutor. He gave me the int main() function which cannot be changed. I was supposed to write the functions etc so that the code would work. Unfortunately I have a seg fault. I've noticed that if the
TSeries series4=series1(2,4);
cout << "Series4: " << series4 << endl;
lines are commented it's more or less working. I would be very grateful for your help.
#include <iostream>
class TSeries {
public:
TSeries()
{
_size = 0;
_capacity = 0;
_tab = NULL;
}
TSeries(float *tab, const int size)
{
_tab = new float[size];
for (int i = 0; i < size; i++) _tab[i] = tab[i];
_size = size;
_capacity = 0;
}
~TSeries() { delete[] _tab; }
TSeries & operator+=(float value) { return insert(value); }
TSeries & operator,(float value) { return insert(value); }
TSeries & operator+(const TSeries & s)
{
// if(this->_size != s._size) std::cout<<"Size doesn't match!"<<std::endl;
/*else
{
std::cout<<"whee";
for(int i; i<this->_size;i++)
{
//this->_tab[i] += s._tab[i];
std::cout<<"nothing";
}
return *this;
}*/
//std::cout<<"sth";
}
TSeries & operator()(int position1, int position2)
{
// return *this;
}
TSeries & insert(float k)
{
if (_size >= _capacity) Enlarge();
_tab[_size++] = k;
return *this;
}
friend std::ostream & operator<<(std::ostream & out, const TSeries & s);
private:
int _size, _capacity;
float *_tab, *_itr;
static int _nr;
void Enlarge()
{
_capacity = 2 * _capacity + 1;
float *tmp = new float[_capacity];
for (int i = 0; i < _size; ++i)
{
tmp[i] = _tab[i];
}
delete[] _tab;
_tab = tmp;
}
};
std::ostream & operator<<(std::ostream & out, const TSeries & s)
{
int przedostatni = s._size - 1;
out << "(";
for (int i = 0; i < s._size; i++)
{
out << (int)s._tab[i];
if (i != przedostatni)
out << ",";
}
out << ")" << std::endl;
}
using namespace std;
int main(int argc, char **argv) {
TSeries series1;
series1 += 1., 2., 4., 2.;
cout << "Series1: " << series1 << endl;
const int size = 7;
float tab[size] = { 3.,3.,3.,4.,5.,1.,0. };
const TSeries series2(tab, size);
cout << "Series2: " << series2 << endl << endl;
TSeries series3 = series1 + series2;
cout << "Series3: " << series3 << endl << endl;
series1 += 1., 0., 3.;
series3 = series1 + series2;
cout << " " << series1 << endl;
cout << " +" << series2 << endl;
cout << " ---------------------" << endl;
cout << "Series3: " << series3 << endl << endl;
TSeries series4 = series1(2, 4);
cout << "Series4: " << series4 << endl;
return 0;
}
/* output required:
Series1: (1,2,4,2)
Series2: (3,3,3,4,5,1,0)
Size doesn't match!
Series3: ()
(1,2,4,2,1,0,3)
+(3,3,3,4,5,1,0)
---------------------
Series3: (4,5,7,6,6,1,3)
Series4: (4,2)
*/
std::ostream & operator<<(std::ostream & out, const TSeries & s) doesn't return anything. Please add a return out at the end of the function
operator() and operator+ should both end with return *this
As Devolus already pointed out: You don't have a copy constructor and no operator=(const TSeries&) defined
You can use memcpy to copy the arrays faster.#
The i in the for-loop in operator+(const TSeries&) isn't initialized.
Your operator(int, int) does currently alter the original object. This doesn't seem right.
Code:
#include <iostream>
class TSeries {
public:
TSeries()
{
_size = 0;
_capacity = 0;
_tab = NULL;
}
TSeries(float *tab, const int size)
{
_size = size;
_capacity = 0;
_tab = new float[size];
memcpy(_tab, tab, _size*sizeof(float));
}
TSeries(const TSeries& other)
{
_size = other._size;
_capacity = other._capacity;
_tab = new float[_size];
memcpy(_tab, other._tab, _size*sizeof(float));
}
~TSeries()
{
delete[] _tab;
}
TSeries & operator+=(float value) { return insert(value); }
TSeries & operator,(float value) { return insert(value); }
TSeries & operator+(const TSeries & other)
{
if (this->_size != other._size)
{
std::cout << "Size doesn't match!" << std::endl;
}
else
{
//std::cout << "whee";
for (int i = 0; i < this->_size; i++)
{
_tab[i] += other._tab[i];
//std::cout << "nothing";
}
}
//std::cout<<"sth";
return *this;
}
TSeries& operator=(const TSeries& other)
{
_size = other._size;
_capacity = other._capacity;
//Create tmp in case of self-assignment
float *tmp = new float[_capacity];
memcpy(tmp, other._tab, _size*sizeof(float));
delete[] _tab;
_tab = tmp;
return *this;
}
TSeries operator()(int position1, int position2)
{
//TODO: Range-Check
return TSeries(_tab + position1, position2 - position1);
}
TSeries & insert(float k)
{
if (_size >= _capacity) Enlarge();
_tab[_size++] = k;
return *this;
}
friend std::ostream & operator<<(std::ostream & out, const TSeries & s);
private:
int _size, _capacity;
float *_tab, *_itr;
static int _nr;
void Enlarge()
{
_capacity = 2 * _capacity + 1;
float *tmp = new float[_capacity];
memcpy(tmp, _tab, _size*sizeof(float));
delete[] _tab;
_tab = tmp;
}
};
std::ostream & operator<<(std::ostream & out, const TSeries & s)
{
int przedostatni = s._size - 1;
out << "(";
for (int i = 0; i < s._size; i++)
{
out << (int)s._tab[i];
if (i != przedostatni)
out << ",";
}
out << ")" << std::endl;
return out;
}
using namespace std;
int main(int argc, char **argv) {
TSeries series1;
series1 += 1., 2., 4., 2.;
cout << "Series1: " << series1 << endl;
const int size = 7;
float tab[size] = { 3.,3.,3.,4.,5.,1.,0. };
const TSeries series2(tab, size);
cout << "Series2: " << series2 << endl << endl;
TSeries series3 = series1 + series2;
cout << "Series3: " << series3 << endl << endl;
series1 += 1., 0., 3.;
series3 = series1 + series2;
cout << " " << series1 << endl;
cout << " +" << series2 << endl;
cout << " ---------------------" << endl;
cout << "Series3: " << series3 << endl << endl;
TSeries series4 = series1(2, 4);
cout << "Series4: " << series4 << endl;
return 0;
}
/* output required:
Series1: (1,2,4,2)
Series2: (3,3,3,4,5,1,0)
Size doesn't match!
Series3: ()
(1,2,4,2,1,0,3)
+(3,3,3,4,5,1,0)
---------------------
Series3: (4,5,7,6,6,1,3)
Series4: (4,2)
*/
Output
Series1: (1,2,4,2)
Series2: (3,3,3,4,5,1,0)
Size doesn't match!
Series3: (1,2,4,2)
(4,5,7,6,6,1,3)
+(3,3,3,4,5,1,0)
---------------------
Series3: (4,5,7,6,6,1,3)
Series4: (7,6)
UPDATE:
Your operator+(const TSeries &) should look somewhat like this:
TSeries operator+(const TSeries & other)
{
if (this->_size != other._size)
{
std::cout << "Size doesn't match!" << std::endl;
return TSeries(); //Return empty object
}
TSeries tmp(*this); //Create copy
for (int i = 0; i < tmp._size; i++)
{
tmp._tab[i] += other._tab[i];
}
return tmp;
}
And your operator()(int, int) like this:
TSeries operator()(int position1, int position2)
{
if (position1 < 0) position1 = 0;
else if (position1 >= _size) position1 = _size - 1;
if (position2 < position1) position2 = position1;
else if (position2 >= _size) position2 = _size - 1;
return TSeries(_tab + position1, position2 - position1);
}
Maybe you want to throw exceptions in the error cases?
So after coding this I got an error : C++ none of the 3 overloads could convert all the argument types line 39 1 in w5.cpp
do you know where is the problem? and could you help me to fix it? I actually dont know why it is showing this because I got the default constructor for this code.
//w5.h
#define MAX_LINE_LENGTH 256
#define MAX_PURCHASES 5
// w5.cpp
#include <iostream>
#include <cstring>
#include "w5.h"
#include "CreditStatement.h"
using namespace std;
void sort(CreditStatement* statement, int n);
int main()
{
double price;
int n = 0;
CreditStatement statement[MAX_PURCHASES];
cout << "Credit Statement Processor\n";
cout << "==========================\n";
do
{
cout << "Item price (0 to quit): ";
cin >> price;
if (cin.fail() || (cin.get() != '\n'))
{
cin.ignore(2000, '\n');
cerr << "Bad character. Try again." << endl;
cin.clear();
}
else if ((int)price != 0)
{
cout << "Statement item: ";
char item[MAX_LINE_LENGTH];
cin.getline(item, MAX_LINE_LENGTH);
if (strlen(item) > 0)
{
statement[n] = CreditStatement(item, price);
n++;
}
}
} while ((int)price != 0 && n < MAX_PURCHASES);
cout << endl;
sort(statement, n);
cout << " Credit Statement\n\n";
cout << " Item Price\n";
cout << "----------------------------------\n";
for (int i = 0; i < n; i++)
{
statement[i].display();
}
cout << endl;
return 0;
}
// sort sorts the elements of Credit Card Statement[n] in ascending order
//
void sort(CreditStatement* s, int n)
{
int i, j;
CreditStatement temp;
for (i = n - 1; i > 0; i--)
{
for (j = 0; j < i; j++)
{
if (s[j].isGreaterThan(s[j + 1]))
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
}
//CreditStatement.h
class CreditStatement{
bool _valid;
double* _price;
char* _item;
public:
CreditStatement();
CreditStatement(char*, double*);
CreditStatement(const CreditStatement&);
CreditStatement& operator=(const CreditStatement&);
//output
void display() const;
//mutators
bool isGreaterThan(const CreditStatement&) const;
};
//CreditStatement.cpp
#include <iostream>
#include <new>
#include "CreditStatement.h"
using namespace std;
void CreditStatement::display() const{
cout << " Something" << _price << _item;
}
bool CreditStatement::isGreaterThan(const CreditStatement&) const{
return _valid;
}
CreditStatement::CreditStatement(){
_item = NULL;
_price = NULL;
}
CreditStatement::CreditStatement(char* iP, double* pP){
_price = NULL;
_item = NULL;
if (pP != NULL){
int sizepP = sizeof(pP) / sizeof(pP[0]);
_price = new (nothrow) double[sizepP];
if (_price){
for (int i = 0; i <sizepP; i++){
_price[i] = pP[i];
};
}
if (iP != NULL){
int sizeiP = sizeof(iP) / sizeof(iP[0]);
_item = new (nothrow) char [sizeiP];
if (_item){
for (int i = 0; i < sizeiP; i++){
_item[i] = iP[i];
};
}
}
}
}
CreditStatement::CreditStatement(const CreditStatement& otherCS){
*this = CreditStatement(otherCS._item, otherCS._price);
}
CreditStatement& CreditStatement::operator=(const CreditStatement& otherCS){
if (this != &otherCS)
{
if (_item){
delete[] _item;
_item = NULL;
}
if (_price){
delete[] _price;
_price = NULL;
}
else{
if (otherCS._price != NULL){
int sizepP = sizeof(otherCS._price) / sizeof(otherCS._price[0]);
_price = new (nothrow) double[sizepP];
if (_price){
for (int i = 0; i < sizepP; i++){
_price[i] = otherCS._price[i];
};
}
if (otherCS._item != NULL){
int sizeiP = sizeof(otherCS._item) / sizeof(otherCS._item[0]);
_item = new (nothrow) char[sizeiP];
if (_item){
for (int i = 0; i < sizeiP; i++){
_item[i] = otherCS._item[i];
};
}
}
}
}
}
return *this;
}
I also got this error
"no instance of constructor "CreditStatement::CreditStatement" matches the argument list
argument types are: (char [256], double) c:*\Project1\w5.cpp 38 20.
I think the problem is your call statement[n] = CreditStatement(item, price);
Here, price is a double, but there's a constructor CreditStatement(char*, double*); but none with signature CreditStatement(char*, double);
You might want to fix that.
i have a c2280 error in c++ and i don't know how to solve it.
here is the code:
#include <iostream>
#include <queue>
#include <deque>
#include "State.h"
#include <assert.h>
#define MAXIMUM_NUMBER_OF_STATES 1000
#define DELTA_Q 0.1
using namespace std;
class RRT
{
private:
float inc_dist;
State start;
State goal;
deque<State> states = deque<State>();
bool goal_is_reached = false;
float RRT::random(float min, float max){
// check if min is less than max , if not then exception is thrown
assert(max >= min);
float range = max - min;
float random;
random = rand() / RAND_MAX;
return (random * (range)) + min;
}
State RRT::randomState(State current_state){
State state = State();
srand(time(0));
while (inStates(state))
{
state.x = random(min(current_state.x, goal.x), max(current_state.x, goal.x));
state.y = random(min(current_state.y, goal.y), max(current_state.y, goal.y));
state.z = random(min(current_state.z, goal.z), max(current_state.z, goal.z));
}
return state;
}
bool RRT::inStates(State state){
for (int i = 0; i < states.size(); i++){
if (states.at(i).x == state.x && states.at(i).y == state.y && states.at(i).z==state.z)
return true;
}
return false;
}
bool RRT::goalTest(State state){
if (state.x == goal.x && state.y == goal.y && state.z == goal.z){
return true;
}
else
return false;
}
void RRT::Successor(State state){
State temp3;
State temp2;
cout <<endl<< "was"<<endl;
if (goalTest(state) || states.size() == MAXIMUM_NUMBER_OF_STATES){
return;
}
getNearistNeighbor(temp3=randomState(state));
cout << "random x: " << temp3.x << " random y: " << temp3.y << " random z: " << temp3.z << endl;
temp2 = State(temp3);
temp2.setFather(state);
states.push_back(temp2);
states.back().setFather(state);
Successor(states.back());
return;
}
State RRT::getNearistNeighbor(State sub_goal_state){
float min_dist = 0, temp;
State desired_state;
for (int i = 0; i < states.size(); i++){
temp = distanceBetweenTwoStates(states.at(i), sub_goal_state);
if (temp < min_dist){
min_dist = temp;
desired_state = State(states.at(i));
}
}
return desired_state;
}
void RRT::generatePath(State state){
cout << endl << "1" << endl;
if (!state.checkIfNull()){
cout << endl << "end" << endl;
return;
cout << endl << "2" << endl;
generatePath(*state.getFather().get());
path.push_back(state);
}
cout << endl << "2" << endl;
generatePath(*state.getFather().get());
path.push_back(state);
return;
}
float RRT::distanceBetweenTwoStates(State state1, State state2){
float x_distance, y_distance, z_distance;
x_distance = sqrt(pow((state1.x - state2.x), 2));
y_distance = sqrt(pow((state1.y - state2.y), 2));
z_distance = sqrt(pow((state1.z - state2.z), 2));
return x_distance + y_distance + z_distance;
}
public:
deque<State> path = deque<State>();
deque<float*> xyzs = deque<float*>();
RRT::RRT(){
}
RRT::RRT(float* starting_point, float* goal_point)
{
start = State(starting_point);
goal= State(goal_point);
states.push_back(start);
}
deque<float*> RRT::getPath(){
Successor(start);
for (int i = 0; i < states.size();i++)
{
if (goalTest(states.at(i))){
goal_is_reached = true;
path.push_back(states.at(i));
break;
}
}
if (goal_is_reached==false){
path.push_back(getNearistNeighbor(goal));
}
State state;
state=State(path.at(0));
path.pop_front();
cout << endl << "x: " << state.x;
cout << endl << "y: " << state.y;
cout << endl << "z: " << state.z << endl;
generatePath(state);
convertToXYZ();
return xyzs;
}
void convertToXYZ(){
State temp;
float* xyz = new float[3];
for (int i = 0; i < path.size(); i++){
temp = path.at(i);
xyz[0] = temp.x;
xyz[1] = temp.y;
xyz[3] = temp.z;
xyzs.push_back(xyz);
}
}
};
here is the code for State.h:
#include <memory>
using namespace std;
class State
{
private:
unique_ptr<State> father;
public:
float x;
float y;
float z;
State(float *xyz){
x = 0;
y = 0;
z = 0;
father = NULL;
}
State(){
x = 0;
y = 0;
z = 0;
father = NULL;
}
State(State& state) : father(new State(*state.father)), x(state.x), y(state.y), z(state.z) {}
State(unique_ptr<State>& state) : father(new State(*state.get())){}
void setFather(State& state){
father.reset(new State(state));
}
unique_ptr<State> getFather(){
unique_ptr<State> temp(new State(*this));
return temp;
}
bool checkIfNull(){
if (father){
return true;
}
else
return false;
}
};
i have been trying to solve this problem but i have not succeed so i need your help guys please help me in solving this.
thanks in advance.
here is the error:
Error 8 error C2280: 'std::unique_ptr<State,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function c:\users\userr\documents\visual studio 2013\projects\devo controller\devo controller\rrt.h 186 1 Devo Controller
again thanks in advance.
unique_ptr<State> getFather(){
unique_ptr<State> temp(new State(*this));
return temp;
}
you can't return unique_ptr . returning a value from function means using the copy constructor. the copy constructor is disabled for unique_ptr. why? because you can't copy a unique_ptr , it's unique! you need to use shared_ptr if many pointers are to point to a specific object. the same goes for the assignment operator ( = ) .
PS. I think it's deprecated to explicitly assign object memory addres to unique_ptr (with new) , the new standard forces you to use std::make_unique in order to assign something to unique_ptr.
also, try googling your error first, you'll be surprised how many answers there are out there