How to define copy constructor and deallocate pointer - class

I ran cppcheck, and it turns out that I need to have a copy constructor for this class. I do not know how to define a copy constructor in this case. Any suggestions?
class Simulator{
private:
int xMax;// = 40; //SIZE;
int yMax;// = 40; //xMax; // 40
//int TTMxSize = 4000;
//const int CarMxSize = 500;
//const int WaitListSize = 4000;
double base_price;// = 0.85 / 4;
double saev_vott;// = 0.35;
char* mode_output;// = "modeChoiceStats_supply_charge.csv";
vector<Car>** CarMx;//[xMax][yMax];
vector <Station>** ChStMx;//[xMax][yMax];
vector<int> **cellChargeCount;
vector<int> **cellChargeTime;
int timeTripCounts [288];
// Functions for program
public:
Simulator();
Simulator(int fleet_size, int seed, char* inputFile);
~Simulator();
bool loadParameters(char* input);
void printParameters();
void placeInitCars();
bool lookForCar (int x, int y, int r, int dist, int& cn);
void assignCar (int x, int y, int c, Trip* trp);
void setBusinessTripProbability();
void runSimulation();
};
Simulator::~Simulator()
{
for (int x=0; x<xMax; x++)
{
delete [] CarMx[x];
delete [] ChStMx[x];
delete [] cellChargeCount[x];
delete [] cellChargeTime[x];
}
for (int x=0; x<numZonesL; x++)
delete [] zoneSharesL[x];
for (int x=0; x<numZonesS; x++)
delete [] zoneSharesS[x];
delete [] CarMx;
delete [] ChStMx;
delete [] cellChargeCount;
delete [] cellChargeTime;
delete [] zoneSharesL;
delete [] zoneSharesS;
}
Also, I am getting Resource Leak error in the following function
bool Simulator::loadParameters(char* input)
{
FILE* inputfile;
inputfile = fopen(input, "r");
if (inputfile == NULL){
cout << "Could not open "<<input<<endl;
return false;
}
double inputVal = -1.0;
char* varStr;
char* valStr;
char instring [80];
while (!feof(inputfile))
{
fgets(instring, 80, inputfile);
comment = instring[0];
if (comment != '#' && comment != '\n')
{
varStr = strtok(instring, "=");
valStr = strtok(NULL, "\0");
if (strcmp (varStr, "xMax") == 0) {
inputVal = strtod(valStr, NULL);
xMax = 4 * (int) inputVal;
} else if (strcmp (varStr, "yMax") == 0) {
inputVal = strtod(valStr, NULL);
yMax = 4 * (int) inputVal;
}
}
return true; <<<<<<<<< RESOURCE LEAK: inputfile
}
Possible leak in this function: Pointer is not deallocated before being allocated.
void Simulator::setBusinessTripProbability()
{
businessTripProbability = new double[926];
businessTripProbability [ 0 ] = 0.0000 ;
businessTripProbability [ 1 ] = 0.0029 ;
businessTripProbability [ 2 ] = 0.0059 ;........... until [925]

I am a Cppcheck developer.
To create a copy constructor:
Simulator(const Simulator &sim);
If you do not plan to use the copy constructor, it's better to delete it:
Simulator(const Simulator &) = delete;
Resource leak: You need to use fclose(inputfile)
Possible leak: Imagine this code:
Simulator simulator;
simulator.setBusinessTripPossibility();
simulator.setBusinessTripPossibility();
There is a memory leak here. The businessTripProbability is allocated twice and there is no deallocation. You might have a rule that the public method setBusinessTripPossibility() will never be called twice. But in my humble opinion you should not design classes with such rule. Try to allow arbitrary use of the public class interface.

Related

Sort an array A using Quick Sort. Using reccursion

#include<iostream>
using namespace std;
void quickSort(int input[], int start, int end)
{
// your code goes here
}
void quickSort(int input[], int size)
{
quickSort(input, 0, size - 1);
}
*/
void swap(int* a,int* b){
int temp=*a;
*a=*b;
*b=temp;
}
int count(int input[],int start,int end ){
static int c=0;
if(start==end)
return c;
if(input[start]>input[end])
c++;
return count(input,start,end-1);
}
int partionArray(int input[],int start,int end ){
int c=count(input,start,end);
int pi=c+start;
swap(&input[start],&input[pi]);
int i=start;
int j=end;
while(i<pi&&j>pi)
{
if(input[i]<input[pi])
{
i++;
}
else if(input[j]>=input[pi])
{
j--;
}
else
{
swap(&input[i],&input[j]);
i++;
j--;
}
}
return pi;
}
void qs(int input[],int start, int end){
if(start>=end)
return;
int pi=partionArray(input,start,end);
qs(input,start,pi-1);
qs(input,pi+1,end);
}
void quickSort(int input[], int size) {
qs(input,0,size-1);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
quickSort(input, n);
for(int i = 0; i < n; i++) {
cout << input[i] << " ";
}
delete [] input;
}
Sort an array A using Quick Sort. Using reccursion is the question.
Input format :
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Output format :
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
What did i do wrong in this code pls can any one explain?Is every thing right with this code?

Implementation of Dijkstra’s mutual exclusion algorithm

I am trying to implement a Dijkstra's algorithm into a fork/join threadpool (consists the main threadpool with a global task queue and N threads with its own task queue) based on Dijkstra's Solution of a problem in concurrent programming control and Frigo's and Leiserson's and Randall's The implementation of the cilk-5 multithreaded language.
But, it seems too complicated. So, I used Filter Lock from Art of Multiprocessor Programming as following:
Book's implementation
class Filter implements Lock {
int[] level;
int[] victim;
public Filter(int n) {
level = new int[n];
victim = new int[n]; // use 1..n-1
for (int i = 0; i < n; i++) {
level[i] = 0;
}
}
public void lock() {
int me = ThreadID.get();
for (int i = 1; i < n; i++) { //attempt level 1
level[me] = i;
victim[i] = me;
// spin while conflicts exist
while ((∃k != me) (level[k] >= i && victim[i] == me)) {};
}
}
public void unlock() {
int me = ThreadID.get();
level[me] = 0;
}
}
My implementation in threadpool
static int* flag;
static int* victim;
const int MAX = 1e9;
int ans = 0;
int nthreads = 10;
struct pt
{
int id;
pthread_t thread;
};
static bool existK(int j, int i, int nthreads){
for (int k = 0; k < nthreads ; k++){
if (flag[k] >= j && k != i)
{
return true;
}
}
return false;
}
void lock_init(void)
{
flag = (int *) calloc(nthreads, sizeof(int));
victim = (int *) calloc(nthreads, sizeof(int));
}
// Executed before entering critical section
void lock(int i)
{
for (int j = 1; j < nthreads; j++){
flag[i] = j;
victim[j] = i;
while (existK(j, i, nthreads) && victim[j] == i);
}
}
// Executed after leaving critical section
void unlock(int i)
{
flag[i] = 0;
}
// in main()
void* func(void *pw)
{
while (true) {
lock(threadID);
// working on its own queue if there is a task and
// after it finishes this task, call unlock(threadID) and call continue;
//if the global queue has tasks left, work on it and call unlock and continue
//if the other worker queue has tasks left, work on it and call unlock and continue
}
}
// Driver code
int main()
{
struct pt** ptr;
lock_init();
ptr = ((struct pt **)malloc(sizeof(struct pt *) * nthreads));
for (int i = 0; i < nthreads; i++){
ptr[i] = malloc(sizeof(struct pt));
(ptr[i])->id = i;
pthread_create(&(ptr[i])->thread, NULL, func, ptr[i]);
}
for (int i = 0; i < nthreads; i++){
pthread_join((ptr[i])->thread, NULL);
}
return 0;
}
However, with my implementation, the main loop is much slower than just using the pthread_mutex_lock and pthread_mutex_unlock. I am not sure if I use the algorithm in a wrong place or my algorithm is wrong at this point.
Additionally, I am wondering how to stealing tasks to work on from the
other workers’ queues in an efficient way (locating the worker with available tasks)

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

when launching boost::thread the .exe chrashes

This is my function:
void cmdChangeSett(cmdbuf* cmd_buffer, CTimeTag tagger, uint8_t chNum, int mask) {
double* oldChannelvoltage = new double[chNum];
double* newChannelvoltage = new double[chNum];
bool* oldEdge = new bool[chNum];
bool* newEdge = new bool[chNum];
int newmask;
double chDiff;
int edgeDiff;
int i;
while (runAcquisition) {
for (i = 0; i < chNum; i++) {
cmd_getThresh_getEdge(cmd_buffer, i, oldChannelvoltage, oldEdge);
}
Sleep(500);
newmask = 0;
for (i = 0; i < chNum; i++) {
cmd_getThresh_getEdge(cmd_buffer, i, newChannelvoltage, newEdge);
chDiff = oldChannelvoltage[i] - newChannelvoltage[i];
edgeDiff = oldEdge[i] - newEdge[i];
//printf("\nOld: %.2f, New: %.2f -> DIFF = %.2f", oldChannelvoltage[i], newChannelvoltage[i], diff);
if (chDiff != 0) {
WARN(newChannelvoltage[i] > 1.5, newChannelvoltage[i] = 1.5f, "Threshold of %.2fV exceeds channel %i's max. Rounding to %.2fV.", newChannelvoltage[i], i + 1, 1.5);
WARN(newChannelvoltage[i] < -1.5, newChannelvoltage[i] = -1.5f, "Threshold of %.2fV exceeds channel %i's max. Rounding to %.2fV.", newChannelvoltage[i], i + 1, -1.5);
tagger.SetInputThreshold(i + 1, newChannelvoltage[i]);
}
if (edgeDiff) {
if (!newEdge[i]) newmask += 1 << i;
}
}
if (newmask != mask) {
tagger.SetInversionMask(newmask);
mask = newmask;
}
}
delete[] oldChannelvoltage;
delete[] newChannelvoltage;
delete[] oldEdge;
delete[] newEdge;
}
When I launch the thread from the main() it crashes:
int main(int argc, char** argv) {
int mask = 0;
cmdbuf* cmd_buffer;
CTimeTag tagger;
//some code ....
//......
boost::function<void()> cmdChangeSettThread = boost::bind(&cmdChangeSett,cmd_buffer, tagger, 16, mask);
boost::thread th(cmdChangeSettThread);
//some other code ...
return 0;
}
Any idea ??
I thought the problem was caused by the arrays I'm using in the function but I can't figure out how to solve the problem.
Thank you very much!
You need to wait for the thread to finish in main.
If the thread destructor is called and the thread is still running terminate() is called.
th.join(); // should stop the application crashing.
return 0;
}
PS. None of this is good:
double* oldChannelvoltage = new double[chNum];
double* newChannelvoltage = new double[chNum];
bool* oldEdge = new bool[chNum];
bool* newEdge = new bool[chNum];
Use a vector (or an array).
Get a code review: http://codereview.stackexchange.com
Thank you everybody! I found the problem!! I was stupidly passing the object CTimeTag tagger by value, I'm sorry if I wasn't super clear in presenting the problem!
So now the function definition is:
void cmdChangeSett(cmdbuf* cmd_buffer, CTimeTag *tagger, tt_buf* buffer, uint8_t chNum, int mask)
and when I'm calling it with boost::bind I have:
boost::function<void()> cmdChangeSettThread = boost::bind(&cmdChangeSett,cmd_buffer, &tagger, buffer, 16, mask);
Thank you again!

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type