using destructors in c++ to delete pointers - visual-c++

I have the following:
//in Matrix.h
class Matrix
{
public:
Matrix (int _row1=1, int _col1=1);
Matrix(const Matrix &);
~Matrix();
int row1;
//int row2;
int col1;
double **m;
//other functions and members...
void Print(int id);
}
//In Matrix.cpp
Matrix::Matrix(int _row1, int _col1): row1(_row1),col1(_col1)
{
m=(double **) new double[row1];
for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];
for(long p=0;p<row1;p++) for (long q=0;q<col1;q++) m[p][q]=0.0;
}
//copy constructor
Matrix::Matrix(const Matrix &Mat){
m=(double **) new double[row1];
**m=**Mat.m;// copy the value
}
// Destructor
Matrix::~Matrix(void){
//We need to deallocate our buffer
delete[] *m;
delete [] m;
//Set m to null just in case
m=0;
cout<<" Freeing m "<<endl;
}
void Matrix::Print(int id)
{
cout<<"Element ID: "<<id<<endl;
for(int i=0; i<row1; i++) {
for(int j=0;j<col1;j++) {
cout<<m[i][j];
if(j==col1-1) cout<<"\n";
}
}
system("PAUSE");
}
a call like the following:
elem[e].d0 = matel[i].OrgD;// Both Matrix
elem[e].d0.Print(1); // checking to see if at all copied
fails at:
void Matrix::Print(int id){
//...
cout<<m[i][j];//here
...//
}
in fact it fails where ever m[i][j] is used by other functions.
this only happens if any object is used successively. And this error goes away if I comment
out the destructor. I fail to understand? Any help!
EDIT 1: I have changed the copy constructor to:
Matrix::Matrix(const Matrix &Mat):row1(Mat.row1),col1(Mat.col1)
{
m= new double *[row1];
for(long p=0;p<row1;p++) m[p]=new double [col1];
for(long p=0;p<row1;p++)for (long q=0;q<col1;q++) m[p][q]=Mat.m[p][q];
// copy the Value
}
And have a assignment operator as:
Matrix& Matrix::operator = (const Matrix& o) {
if ( this == &o ) {
return *this; //Self assignment : nothing to do
}
delete[] *m;
delete[] m;
row1 = o.row1;
col1 = o.col1;
m = new double*[row1];
for(long p=0;p<row1;p++) m[p]=new double [col1];
for(long p=0;p<row1;p++) for (long q=0;q<col1;q++) m[p][q]=o.m[p][q];
return *this;
}
Now it fails at:
Matrix::Operator=...
{
o.m[p] 0xcdcdcdcd double *
CXX0030: Error: expression cannot be evaluated // in the debugger
}
I have noticed that the same thing happens form all functions that use '.m' that is m of the calling object is not available if there is the destructor deleting 'm'. Hope to get some answers.

In your constructor you are using
m=(double **) new double[row1];
for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];
new double[row1] is of type double[]. You cast this to double**. You should use new (double*)[row1] here if you really want to get an array of double pointers.

Related

Displaying results in c++

I have a question concerning working with classes in c++. I must say I'm a beginner. For example, i have this class:
class student {
private:
char* name;
public:
int nrcrt;
student() {
name = new char[7];
name = "Anonim";
nrcrt = 0;
}
student(char* n, int n) {
this->name = new char[7];
strcpy(name, n);
nrcrt = nr;
}
~student() {
delete [] name;
}
char* get_name() {
return this->name;
}
}
void main() {
student group[3];
group[0] = student("Ana", 1);
group[1] = student("Alex", 2);
group[2] = student("Liam", 5);
for (i=0; i<3; i++) {
if (group.nrcrt[i] != 0)
cout << group[i].get_name() << Endl;
}
}
My question is why is it displaying different characters?
first of all your code is not working.
3.cpp:40:18: error: request for member ‘nrcrt’ in ‘group’, which is of non-class type ‘student [3]’
if(group.nrcrt[i]!=0)
i is also not declared.please make proper changes.
group.nrcrt[i]
should be changed to:
group[i].nrcrt
When the array is created, your default constructor is used.
When you assign to the elements, your destructor is called, deleting name.
The default constructor is assigning a literal to name, and deleting that memory has undefined behaviour.
In your default constructor, replace
name = "Anonim";
with
strcpy(name, "Anonim");
Your compiler should have warned you about the assignment.
If it didn't, increase the warning level of your compiler.
If it did, start listening to your compiler's warnings.
do not worry. C++ could look a bit scary as first but it is ok when you get into it. First, let's say that all classes it is good to start with upper case letters. Secondly, you have two constructors (default without parameters and one or more with, in our case one). Default consructor you need to declare an array of objects:
Student group[3];
The next important thing is that you then do not need the rest of the constructors in that case.
group[0]=student("Ana",1);
group[1]=student("Alex",2);
group[2]=student("Liam",5);
Remember to include ; at the end of class declaration. To put all the statements and expression throughout your interation within the same loop. Here is what I found as an errors anf fix them. Could probably have more.
class Student
{
private:
char* name;
public:
int nrcrt;
Student()
{
name=new char[7];
strcpy(name, "Anonim");
nrcrt=0;
}
Student( char* n, int n)
{
this->name=new char[7];
strcpy(name, n);
nrcrt=nr;
}
~Student()
{
delete [] name;
}
char* get_name()
{
return this->name;
}
};
int main()
{
Student group[3];
for(int i=0;i<3;i++)
{
if(group.nrcrt[i]!=0)
cout<<group[i].get_name()<<endl;
}
return 0;
}

Copying objects in C++/CLI and message passing in multithreading

I'm trying to transfer a command line code that I have to a more visual program with a
GUI to enable easier use. The original code was in C++, so I'm using Visual C++ that is
available in Visual Studio Express 2012, but I have problems understanding the "new"
managed C++/CLI way of handling objects. Being new to CLI and managed C++, I was wondering
if someone can explain what I am doing wrong, and why it doesn't work. Now here is a
description of the code and the problem.
The program is essentially an optimization program:
There are multiple boxes (modes) in a system, each mode, depending on its type has a
few numerical coefficients that control its behavior and the way it responds to outside
excitation.
The program asks the user to specify the number of boxes and the type of each box.
Then tries to find the numerical coefficients that minimize the difference between
the system response with those obtained experimentally.
So, the UI has means for user to open the experimental result files, specify the number
of modes, and specify the type of each mode. Then, the user can initiate the processing
function by clicking on a start button, that initiates a background worker.
Following the example given in MSDN, I created a class that performs the work:
ref class curveFit
{
public: ref class CurrentState{
public:
int percentage;
int iterationNo;
int stage;
bool done;
multimode systemModel;
};
public:
int modes;
int returncode;
array<double> ^expExcitations;
array<double> ^expResults;
multimode systemModel;
private:
void fcn(int, int, double*, double*, int*);
double totalError(std::vector<double> &);
public:
delegate void fcndelegate(int, int, double*, double*, int*);
public:
curveFit(void);
curveFit^ fit(System::ComponentModel::BackgroundWorker^, System::ComponentModel::DoWorkEventArgs^, Options^);
};
multimode is just a container class: a list of different boxes.
ref class multimode
{
private:
Collections::Generic::List<genericBoxModel ^>^ models;
int modes;
public:
multimode(void);
multimode(const multimode%);
int modeNo(void);
void Add(genericBoxModel^);
void Clear();
genericBoxModel^ operator[](int);
multimode% operator=(const multimode%);
double result(double);
bool isValid();
std::vector<double> MapData();
void MapData(std::vector<double> &);
};
multimode::multimode(void)
{
models = gcnew Collections::Generic::List<genericBoxModel ^>();
modes = 0;
}
multimode::multimode(const multimode% rhs)
{
models = gcnew Collections::Generic::List<genericBoxModel ^>();
for(int ind = 0; ind < rhs.modes; ind++)
models->Add(rhs.models[ind]);
modes = rhs.modes;
}
int multimode::modeNo(void)
{
return modes;
}
void multimode::Add(genericBoxModel^ model)
{
models->Add(model);
modes++;
}
void multimode::Clear()
{
models->Clear();
modes = 0;
}
genericBoxModel^ multimode::operator[](int ind)
{
return models[ind];
}
multimode% multimode::operator=(const multimode% rhs)
{
models->Clear();
for(int ind = 0; ind < rhs.modes; ind++)
models->Add(rhs.models[ind]);
modes = rhs.modes;
return *this;
}
double multimode::result(double excitation)
{
double temp = 0.0;
for(int ind = 0; ind < modes; ind++)
temp += models[ind]->result(excitation);
return temp;
}
bool multimode::isValid()
{
bool isvalid = true;
if(modes < 1)
return false;
for(int ind = 0; ind < modes; ind++)
isvalid = (isvalid && models[ind]->isValid());
return isvalid;
}
std::vector<double> multimode::fullMap()
{
//Map the model coefficients to a vector of doubles
...
}
void multimode::fullMap(std::vector<double> &data)
{
//Map a vector of doubles to the model coefficients
...
}
and genericBoxModel is an abstract class that all box models are based on.
The curvefit::fit function does the optimization based on the options passed to it:
curveFit^ curveFit::fit(System::ComponentModel::BackgroundWorker^ worker, System::ComponentModel::DoWorkEventArgs^ e, Options^ opts)
{
fcndelegate^ del = gcnew fcndelegate(this, &curveFit::fcn);
std::vector<double> data;
CurrentState^ state = gcnew CurrentState;
state->done = false;
state->stage = 0;
state->percentage = 0;
state->systemModel = systemModel;
worker->ReportProgress(state->percentage, state);
switch(opts->optimizationMethod)
{
case 0:
while(iterationNo < maxIterations)
{
data = systemModel.MapData();
OptimizationMethod0::step(some_parameters, data, (optmethods::costfunction)Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(del).ToPointer());
systemModel.MapData(data);
iterationNo++;
state->percentage = 0;
state->systemModel = systemModel;
worker->ReportProgress(state->percentage, state);
}
...
}
}
I'm passing the system model inside the state so that I can display the results of the
latest step on the screen, which doesn't work, but that is another question :-)
The start button calls the curvefit::fit function after initializing the system model:
private: System::Void btnStart_Click(System::Object^ sender, System::EventArgs^ e) {
systemModel.Clear();
for(int mode = 0; mode < modes; mode++)
{
switch(model)
{
case 0:
systemModel.Add(gcnew model0);
systemModel[mode]->coefficients[0] = 100.0 / double(mode + 1);
...
break;
...
}
}
btnStart->Enabled = false;
stStatusText->Text = "Calculating!";
Application::UseWaitCursor = true;
curveFit^ cf = gcnew curveFit;
fitCurve->RunWorkerAsync(cf);
}
private: System::Void fitCurve_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
System::ComponentModel::BackgroundWorker^ worker;
worker = dynamic_cast<System::ComponentModel::BackgroundWorker^>(sender);
curveFit^ cf = safe_cast<curveFit^>(e->Argument);
cf->expExcitations = gcnew array<double>(expExcitations.Count);
expExcitations.CopyTo(cf->expExcitations);
cf->expResults = gcnew array<double>(expResults.Count);
expResults.CopyTo(cf->expResults);
cf->systemModel = systemModel;
cf->modes = modes;
e->Result = cf->fit(worker, e, options);
}
This works perfectly! But, in order to make the optimization process faster and more
successful, I wanted to use the results of previous optimizations as the initial guess
for the next run (if possible):
multimode oldmodel(systemModel);
systemModel.Clear();
for(int mode = 0; mode < modes; mode++)
{
switch(model)
{
case 0:
if(mode < oldmodel.modeNo() && oldmodel.isValid() && (oldmodel[mode]->model == 0))
systemModel.Add(oldmodel[mode]);
else
{
systemModel.Add(gcnew model0);
systemModel[mode]->coefficients[0] = 100.0 / double(mode + 1);
...
}
break;
...
Now, my problem is, after this change, it seems that the messages don't get passed
correctly: the first time the start button is clicked everything functions as it should,
but from then on, if the statement systemModel.Add(oldmodel[mode]); gets executed,
results remain the same as the initial guesses, and don't get updated after the fit
function is called.
So, why should these two lines(Add(oldmodel[mode]) and Add(gcnew model0)) give
such different results?

Multithreading in C++ using reference classes - ThreadStart constructor issues?

I appreciate any help, and would like to thank you in advance. I'm working on a project for one of my classes. Essentially performing merge sort using multithreading and reference classes. In main I'm just trying to create an initial thread that will begin the recursive mergesort. Each time the array is split a new thread is spawned to handle that subroutine. I don't need all of it done, i just don't under stand why my Thread constructor and ThreadStart delegate are not working. Thanks again!!
#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include <cstdlib>
using namespace System;
using namespace System::Threading;
public ref class MergeSort
{
private: int cnt;
public: MergeSort()
{
cnt = 0;
}
public: void mergeSort(char a[], int from, int to)
{
Thread^ current = Thread::CurrentThread;
if(from == to)
return;
int mid = (from + to)/2;
//Sort the first and the second half
//addThread(a, from, mid);
//addThread(a, mid+1, to);
//threads[0]->Join();
//threads[1]->Join();
merge(a, from, mid, to);
}
public: void merge(char a[], int from, int mid, int to)
{
Thread^ current = Thread::CurrentThread;
while (current ->ThreadState == ThreadState::Running)
{
int n = to-from + 1; // Size of range to be merged
std::vector<char> b(n);
int i1 = from; //Next element to consider in the first half
int i2 = mid + 1; //Next element to consider in the second half
int j = 0; //Next open position in b
//As long as neight i1 or i2 is past the end, move the smaller element into b
while(i1 <= mid && i2 <= to)
{
if(a[i1] < a[i2])
{
b[j] = a[i1];
i1++;
}
else
{
b[j] = a[i2];
i2++;
}
j++;
}
//Copy any remaining entries of the first half
while(i1 <= mid)
{
b[j] = a[i1];
i1++;
j++;
}
while(i2 <= to)
{
b[j] = a[i2];
i2++;
j++;
}
//Copy back from temporary vector
for(j = 0; j < n; j++)
a[from+j] = b[j];
}
}
};
void main()
{
char A[10];
for(int i = 0; i < 10; i++)
{
A[i] = ((char) ((rand() % (122-65)) + 65));
}
array<Thread^>^ tr = gcnew array<Thread^>(10);
MergeSort^ ms1 = gcnew MergeSort();
ThreadStart^ TS = gcnew ThreadStart(ms1, &MergeSort::mergeSort(A, 0, 10));
tr[0] = gcnew Thread(TS);
tr[0] -> Start();
system("pause");
}
The issue you are facing here is how to construct a ThreadStart delegate. You are trying to do too many things in the ThreadStart constructor. You cannot pass in arguments at this point because all it is looking for is a start location for the thread.
The delegate should be:
ThreadStart^ TS = gcnew ThreadStart(ms1, &MergeSort::mergeSort);
Since however you are passing in some state, I would recommend doing a bit more research on how that is done using C++\CLI. This MSDN topic should give you a start.
Edit:
Never mind, the problem was that I had to change the parameter of the method I tried to pass from Int32 to Object^.
I´m having a similar issue, though i think my problem are not the arguments. I´m passing those through during thread->Start().
I think my problem is rather that I´m trying to start the thread using a method of a ref class.
invalid delegate initializer -- function does not match the delegate type
Is the error I´m getting. Any Ideas?
void AddForcesAll() {
for (int index = 0; index < n; index++) {
Thread^ thread = gcnew Thread (gcnew ParameterizedThreadStart(this, &Bodies::AddForces));
thread->Start(index);
}
The Syntax worked fine for me for non referenced classes.

Creating a 2 dimensional character array dynamically in C++

I want to create a 2 dimensional character array dynamically through pointers. Then input 10 strings in it and then take a string target from user and find it in array. if it is present then return its index. I have written code for it but it has errors. Please help me in correcting it. Thanks in advance.
#include<iostream>
#include<string>
using namespace std;
int strsearch(char [][50],char *);
int main()
{
char str[10][50];
char *target=new char [50];
int index;
for(int i=0; i<10; i++)
{
str = new char* [50];
str++;
}
for(int i=0; i<10; i++)
{
cout<<"Enter a sting";
cin>>str[i][50];
str++;
}
cout<<"Enter a string to find:";
cin>>target;
index=strsearch(str,target);
if(index<0)
{
cout<<"String not found";
}
else
{
cout<<"String exist at location "<<index<<endl;
}
return 0;
}
int strsearch(char string[10][50],char *fstr)
{
int slen;
for(int i=0;i<10;i++)
{
slen=strlen(**string);
if (strnicmp(*string[50],fstr,slen)== 0)
{
return i;
}
}
return -1;
}
Simply use:
std::vector<std::string> obj;
It will save you all the head & heart aches and guard you against easy to go wrong manual memory management issues. What you are trying to do is to solve the problem C way. With C++ the correct way to do it is using a vector of strings.
I think this is an error in any case:
for(int i=0;i<10;i++)
{
slen=strlen(**string);
if (strnicmp(*string[50],fstr,slen)== 0)
{
return i;
}
}
Must be something like:
for(int i=0;i<10;i++)
{
slen=strlen(string[i]);
if (strnicmp(string[i],fstr,slen)== 0)
{
return i;
}
}
I have done some correction, i think it can help you but i have not compiled to check for errors.
#include<iostream>
#include<string>
#define DIM_1 10 // Avoid to use "magic numbers" in your code
#define DIM_2 50
using namespace std;
int strsearch(char **string,char *fstr);
int main()
{
char **str = new char*[DIM_1]; //char str[10][50]; dynamically allocated array.
char *target=new char [DIM_2];
int index;
for(int i=0; i<DIM_1; i++)
{
str[i] = new char[DIM_2]; //Do not lost the original pointer
//str++;
}
for(int i=0; i<DIM_1; i++)
{
cout<<"Enter a sting";
cin>>str[i][DIM_2];
//str++; Do not lost the original pointer
}
cout<<"Enter a string to find:";
cin>>target;
index=strsearch(str,target);
if(index<0)
{
cout<<"String not found";
}
else
{
cout<<"String exist at location "<<index<<endl;
}
// Free memory!!
for (int i=0; i<DIM_1;i++) delete[] str[i];
delete[] str;
delete[] target;
return 0;
}
int strsearch(char **string,char *fstr) //its dinamicly allocated array
{
int slen;
int result=-1; //Only one return-> structured programming
for(int i=0;i<DIM_1;i++)
{
slen=strlen(**string);
//strlen and strnicmp is C, not C++, check string class.
if (strnicmp(string[i],fstr,DIM_2)== 0) //Find in the string[i]
{
result= i;
}
}
return result;
}

boost::shared_array assignment crashes application(VC++ 2010)

Modified the below circular queue code for my app.
This queue can hold 32 elements max and I have declared the elements as a structure array inside the class. For adding an element to the queue you have to call CreateElement() functions, which checks for a free element and returns an index. When I reuse an element after processing the following line in the CreateElement functions crashes
boost::shared_array<char> tData(new char[bufferSize]);
m_QueueStructure[queueElems].data = tData;
As per documentation, the assignment operator is supposed to destroy the earlier object and assign the new one. Why is it crashing? Can someone tell me where am I screwing?
#include "boost/thread/condition.hpp"
#include "boost/smart_ptr/shared_array.hpp"
#include <queue>
#define MAX_QUEUE_ELEMENTS 32
typedef struct queue_elem
{
bool inUse;
int index;
int packetType;
unsigned long compressedLength;
unsigned long uncompressedLength;
boost::shared_array<char> data;
}Data;
class CQueue
{
private:
int m_CurrentElementsOfQueue;
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
Data m_QueueStructure[MAX_QUEUE_ELEMENTS];
public:
CQueue()
{
m_CurrentElementsOfQueue = 0;
for(int i = 0; i < MAX_QUEUE_ELEMENTS; i++)
{
m_QueueStructure[i].inUse = false;
m_QueueStructure[i].index = i;
}
}
~CQueue()
{
for(int i = 0; i < m_CurrentElementsOfQueue; i++)
{
int index = wait_and_pop();
Data& popped_value = m_QueueStructure[index];
popped_value.inUse = false;
}
m_CurrentElementsOfQueue = 0;
}
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
int wait_and_pop()
{
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
Data& popped_value=the_queue.front();
the_queue.pop();
return popped_value.index;
}
int CreateElement(int bufferSize, unsigned long _compressedLength,
unsigned long _uncompressedLength, int _packetType) /* Send data length for this function */
{
int queueElems = 0;
if(m_CurrentElementsOfQueue == 32)
{
CCommonException ex(QERROR, QUEUE_FULL, "Circular Buffer Queue is full");
throw ex;
}
for(queueElems = 0; queueElems < MAX_QUEUE_ELEMENTS; queueElems++)
{
if(m_QueueStructure[queueElems].inUse == false)
break;
}
boost::shared_array<char> tData(new char[bufferSize]);
m_QueueStructure[queueElems].data = tData;
m_QueueStructure[queueElems].inUse = true;
m_QueueStructure[queueElems].compressedLength = _compressedLength;
m_QueueStructure[queueElems].uncompressedLength = _uncompressedLength;
m_QueueStructure[queueElems].packetType = _packetType;
m_CurrentElementsOfQueue++;
return queueElems;
}
Data& GetElement(int index)
{
Data& DataElement = m_QueueStructure[index];
return DataElement;
}
void ClearElementIndex(Data& delValue)
{
m_CurrentElementsOfQueue--;
delValue.inUse = false;
}
};
for(queueElems = 0; queueElems < MAX_QUEUE_ELEMENTS; queueElems++) after looping queueElems has value 32 but in your m_QueueStructure only 32 elements so you trying to access m_QueueStructure[queueElems].data to 33rd element. That the problem.
EDIT: try use m_QueueStructure[queueElems].data.reset(new char[bufferSize]);
Solved the problem. Two changes I did. In the wait_and_pop function, I was returning an index rather than a Data&. When I returned Data&, that solved the assignment problem. Another crash was happening due to a memset of a shared_array.get(). Lesson learnt, never memset a shared_array or a shared_ptr.

Resources