Char* not retaining text inside my class - initialization constructor problem? - c++

I have the following class (I've trimmed irrelevant stuff):
class Example
{
private:
char* name;
int value[4];
int numVals;
public:
Example();
Example(char name[], int numVals, int, int, int, int);
~Example();
};
And here is the initialization constructor:
Example::Example(char na[], int vals, int v1, int v2, int v3, int v4)
{
name = new char[strlen(na)+1];
strcpy(name, na);
numVals = vals;
value[0] = v1;
value[1] = v2;
value[2] = v3;
value[3] = v4;
// cout << name; // this DOES print out the correct text
}
In my main(), I have an array of Example class, Example myArray[numRecs]. I then have a loop that uses the initialization constructor to fill the array:
myArray[i] = Example(name, numVals, v[0], v[1], v[2], v[3]);
Everything works as expected, however the name does not retain the characters I put into it. I checked using cout what the value is when it is passed into the constructor, and it was correct! However when I use my Example::Print(), it spits out a random character (the same character for each instance of Example).
Here is the Example::Print()
void Example::Print()
{
int total, avg;
total = avg = 0;
cout << left << setw(20) << name << '\t';
for(int i=0; i<4; i++){
if(i<numVals){
cout << left << setw(8) << value[i];
total += value[i];
} else
cout << left << setw(8) << " ";
}
avg = total/numVals;
cout << left << setw(8) << total <<
left << setw(8) << avg << endl;
}
Any ideas? Thanks!
Oh and also, this is for an assignment. We have been told to keep the name field as a char pointer, not a string. I am confused as to what I should be using for the init constructor (char* name or char name[] or.. is there a difference?)
EDIT: Here is the destructor and default constructor. I do not have a copy constructor yet as the assignment does not call for it and it is not used. I'll go ahead and make one for completeness anyway.
Example::~Example()
{
delete [] name;
}
Example::Example()
{
numVals = 0;
for(int i=0; i<4; i++)
value[i] = -1;
}

You should run your program through a memory debugger to witness the nightmare you've created!
You are using manual memory management in your class, yet you forgot to obey the Rule of Three: You didn't implement the copy constructor, assignment operator and destructor! Thus the temporary does allocate memory, copies the pointer (shallowly), and then probably invalidates the memory when it goes out of scope.
The immediate "fix my code" answer is that you have to implement a proper assignment operator and copy constructor to make a deep copy of the char array.
The "this is C++" answer is not to use pointers, new and arrays, and instead std::string.

An easy fix would be to store pointers to the Examples in the array instead of the actual objects. This way, you don't have to deal with copying (which you haven't implemented).

Related

double free while using vector and strings

I wrote the following function and a simple class, while trying to understand how expensive a work with vector can be.
void gen_random(string & str, const int len)
{
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand((unsigned int)time(NULL));
str.reserve(len);
for (int i = 0; i < len; ++i)
{
str += alphanum[rand() % (sizeof(alphanum) - 1)];
}
}
class Person
{
public:
//CTOR with parameter
Person(u_int32_t Id)
{
std::cout << "\033[1;32mPerson CTOR: " << Id << "\033[0m" << std::endl;
m_Id = Id;
m_RandSid = new string;
gen_random(*m_RandSid, 10);
}
//CCTOR
Person(const Person & p)
{
std::cout << "\033[1;31mPerson CCTOR: " << p.m_Id << "\033[0m" << std::endl;
m_Id = p.m_Id;
m_RandSid = p.m_RandSid; //trigger string operator=()
}
//MCTOR
Person(Person&& p)
{
std::cout << "\033[1;34mPerson MCTOR: " << p.m_Id << "\033[0m" << std::endl;
m_Id = p.m_Id;
m_RandSid = p.m_RandSid;
p.m_RandSid = nullptr;
}
//DTOR
~Person()
{
std::cout << "\033[1;33mPerson DTOR: "<<m_Id <<"\033[0m"<< std::endl;
if (nullptr != m_RandSid)
{
delete m_RandSid;
}
}
u_int32_t m_Id;
string * m_RandSid;
};
and driver :
int main()
{
int a;
vector<Person> v;
for (int i = 0; i < 2; ++i)
{
std::cout <<std::endl<< "inserting person #" << i << std::endl;
std::cout << "Vector size = " << v.size()<< " Vector capacity = " << v.capacity() << std ::endl;
v.emplace_back(i);
std::cout << *v[i].m_RandSid << std::endl;
std::cout << "Vector size = " << v.size()<< " Vector capacity = " << v.capacity() << std ::endl;
}
std::cout<<std::endl<<"--------------------------------------------------------"<<std::endl;
return 0;
}
when I run this program, I the following output:
inserting person #0
Vector size = 0 Vector capacity = 0
Person CTOR: 0
07QoUmgEe6
Vector size = 1 Vector capacity = 1
inserting person #1
Vector size = 1 Vector capacity = 1
Person CTOR: 1
Person CCTOR: 0
Person DTOR: 0
07QoUmgEe6
Vector size = 2 Vector capacity = 2
--------------------------------------------------------
Person DTOR: 0
free(): double free detected in tcache 2
I don't understand where else I perform another free :\
The other problem is that the string is randomized per execution and not per object,
If srand is performed on each execution, why all the string look the same ?
In your copy and move constructor you simply copy raw pointers, which makes 2 pointers to point to the same memory, and when both objects destroyed you get double deallocation:
Person(const Person & p)
{
std::cout << "\033[1;31mPerson CCTOR: " << p.m_Id << "\033[0m" << std::endl;
m_Id = p.m_Id;
m_RandSid = p.m_RandSid; // now both pointers point to the same memory
}
It is not clear why you need dynamically allocated string objects, you should just store objects by value, but if you do need that you should use smart pointers (either std::shared_ptr or std::unique_ptr depends of what ownership you need). That will not only make your problem disappear but you would not have to provide copy and move constructor manually, compiler generated ones would be sufficient.
Note, your class is also missing proper copy and move assignment operator, though it is not exposed in code shown it still violates the rule of three/five/zero and you may have problems with your code later.
Your copy constructor copies the pointer value, and should be doing a deep copy (allocate a new string). In a simple design like this I would avoid using new/free for the string.
You initialize (actually reset) rand with time with second precision - time(). Your app probably finishes in less than a second, hence the similar strings. Initialize rand only once, eg when starting the app.

Homework: C++ reverse string by swapping characters using pointers

I have program that will swap all of the characters in strings using pointers. My problem occurs when I try to delete the pointers and deallocate the memory. I get an invalid pointer error, even when I try and delete the pointer right after I create them. This is a computer science course activity that must be done like this, it is not for a grade, I just want to learn from whatever mistake I am making.
#include <iostream>
using namespace std;
int main() {
string s;
cin >> s;
char a = 'a';
char b = 'b';
char *c1 = &a, *c2 = &b;
int len = s.length();
for (int i = 0; i < len; i++) {
char temp;
*c1 = s[i];
*c2 = s[(len - i) -1];
cout << "c1 " << *c1 << endl << "c2 " << *c2 << endl;
temp = *c1;
*c1 = *c2;
*c2 = temp;
if (i == len - 1) {
cout << "Should be deallocating memory" << endl;
delete c1, c2;
cout << "Set to null" << endl;
c1 = NULL;
c2 = NULL;
}
}
cout << "s " << s << endl;
return 0;
}
new allocates memory, and you haven't done that. Nor should you. Your memory is allocated as part of the std::string object, and will be automatically removed when it goes out of scope.
See RAII.
At this stage, there is probably no need for you to use new or delete, you should just use the standard classes like std::string and std::vector<T>. If you ever do, it's likely you should only do so inside a constructor and destructor. There may be rare cases where this doesn't apply, but in those cases you should be very careful not to leak on an exception being calls. This isn't one of those rare cases, indeed it's far from it.

Array of pointers segfault

I'm not entirely sure why I'm getting a segfault for this piece of code. I have an array of object pointers I want to create. Here is my code.
edge **test = new edge*[a]; //Edge is a predefined class I have created. a is a my size of my array.
graphCreate2(test, vertices, roads, a); //Note roads is an edge class I have already created also
However, when I try to access edge ** test's elements, I get a segfault. Here's how I accessed it.
void graphCreate2(edge **test, int vertices, edge *roads, int a)
{
for(int i = 0; i < a; i++)
{
e[i]->setEdgeSrc(roads[i].getEdgeSrc());
e[i]->setEdgeDes(roads[i].getEdgeDes());
e[i]->setLength(roads[i].getLength());
cout << e[i]->getLength() << " " << e[i]->getEdgeSrc() << " " << endl;
}
}
Might anyone know why I'm getting this segfault? I thought I allocated memory to it as the constructor is called when creating the array Thanks!
The constructor is not called for each edge. You're only creating the array of pointers, but they point to garbage.
You need to create them all in a loop.
void graphCreate2(edge **test, int vertices, edge *roads, int a)
{
for(int i = 0; i < a; i++)
{
test[i] = new edge(); // create the edge
test[i]->setEdgeSrc(roads[i].getEdgeSrc());
test[i]->setEdgeDes(roads[i].getEdgeDes());
test[i]->setLength(roads[i].getLength());
cout << test[i]->getLength() << " " << test[i]->getEdgeSrc() << " " << endl;
}
}

C++: Why is my vector of structs acting as one struct?

I'm working my way through Accelerated C++ and have decided to mess around with the one of structs that were defined in there. While doing so, I've come across a problem: creating a vector of these structs and modifying the elements in each one seems to modify the elements in all of them.
I realize that this probably means I've initialized all the structs in the vector to a struct at a single memory address, but I used the .push_back() method to insert "dummy" structs in to the vector. I was under the impression that .push_back() pushes a copy of its argument, effectively creating a new struct.
Here is the header for the struct:
#ifndef _STUDENT_INFO__CHAPTER_9_H
#define _STUDENT_INFO__CHAPTER_9_H
#include <string>
#include <iostream>
#include <vector>
class Student_info9{
public:
Student_info9(){homework = new std::vector<double>;};
Student_info9(std::istream& is);
std::string getName() const {return name;};
double getMidterm() const {return midterm;};
double getFinal() const {return final;};
char getPassFail() const {return passFail;};
std::vector<double> *getHw(){return homework;};
void setName(std::string n) {name = n;};
void setMidterm(double m) {midterm = m;};
void setFinal(double f) {final = f;};
private:
std::string name;
double midterm;
double final;
char passFail;
std::vector<double> *homework;
};
#endif /* _STUDENT_INFO__CHAPTER_9_H */
And here is the code that i'm fooling around with (excuse the excessive print statements... the result of some time trying to debug :) ):
vector<Student_info9> did9, didnt9;
bool did_all_hw9(Student_info9& s)
{
vector<double>::const_iterator beginCpy = s.getHw()->begin();
vector<double>::const_iterator endCpy = s.getHw()->end();
return(find(beginCpy, endCpy, 0) == s.getHw()->end());
}
void fill_did_and_didnt9(vector<Student_info9> allRecords)
{
vector<Student_info9>::iterator firstDidnt = partition(allRecords.begin(), allRecords.end(), did_all_hw9);
vector<Student_info9> didcpy(allRecords.begin(), firstDidnt);
did9 = didcpy;
vector<Student_info9> didntcpy(firstDidnt, allRecords.end());
didnt9 = didntcpy;
}
int main(int argc, char** argv) {
vector<Student_info9> students;
Student_info9 record;
for(int i = 0; i < 5; i++)
{
students.push_back(record);
}
for(int i = 0; i < students.size(); i++)
{
students[i].setMidterm(85);
students[i].setFinal(90);
students[i].getHw()->push_back(90);
std::cout << "student[" << i << "]'s homework vector size is " << students[i].getHw()->size() << std::endl;
students[i].getHw()->push_back(80);
std::cout << "student[" << i << "]'s homework vector size is " << students[i].getHw()->size() << std::endl;
students[i].getHw()->push_back(70);
std::cout << "student[" << i << "]'s homework vector size is " << students[i].getHw()->size() << std::endl;
std::cout << "Just pushed back students[" << i << "]'s homework grades" << std::endl;
if(i == 3)
students[i].getHw()->push_back(0);
}
std::cout << "student[3]'s homework vector size is " << students[3].getHw()->size() << std::endl;
for(vector<double>::const_iterator it = students[3].getHw()->begin(); it != students[3].getHw()->end(); it++)
std::cout << *it << " ";
std::cout << std::endl;
std::cout << "students[3] has " << ( ( find(students[3].getHw()->begin(),students[3].getHw()->end(), 0) != students[3].getHw()->end()) ? "atleast one " : "no " )
<< "homework with a grade of 0" << std::endl;
fill_did_and_didnt9(students);
std::cout << "did9's size is: " << did9.size() << std::endl;
std::cout << "didnt9's size is: " << didnt9.size() << std::endl;
}
As you can see by the print statements, it seems that the homework grades are being added only to one Student_info9 object, copies of which seem to be populating the entire vector. I was under the impression that if you were to use consecutive copies of .push_back() on a single object, it would create copies of that object, each with different memory addresses.
I'm not sure if that's the source of the problem, but hopefully someone could point me in the right direction.
Thanks.
When you push a StudentInfo onto the vector, it is indeed copied, so that's not the problem. The problem is the vector containing the homework grades. Since you only store a pointer to that vector in StudentInfo, only the pointer, not the vector, is copied when you copy a StudentInfo. In other words you have many different StudentInfos that all have a pointer to the same homework vector.
To fix this you should define a copy constructor which takes care of copying the homework vector.
Have you learned about the copy constructor yet? If so, think about what is happening with vector<Student_info9> students on push_back().
Specifically, what happens with this pointer.
std::vector<double> *homework;
The line Student_info9 record; constructs a Student_info9 using the first constructor. This first constructor creates a vector and stores a pointer to it as a member variable. You then proceed to add a copy of this Student_info9 to a vector 5 times. Each copy has a pointer to the same vector.
Your StudentInfo9 class contanis a pointer to a std::vector<double>, which means in the default copy constructor (which will be called when you add a StudentInfo9 object to your vector), the pointer itself is copied. That means all of your StudentInfo9 objects have the same homework vector.
Does that make sense? Please refer to http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/CLASSES-PTRS.html for a more in depth look at pointers and copy constructors.

Constructors taking references in C++

I'm trying to create constructor taking reference to an object. After creating object using reference I need to prints field values of both objects. Then I must delete first object, and once again show values of fields of both objects. My class Person looks like this :
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
~Person(){
cout << "Destroying resources" << endl;
delete[] name;
delete age;
}
void init(char* n, int a) {
name = n;
age = a;
}
};
Here's my implementation (with the use of function show() ). My professor said that if this task is written correctly it will return an error.
#include <iostream>
using namespace std;
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
Person(const Person& p){
name = p.name;
age = p.age;
}
~Person(){
cout << "Destroying resources" << endl;
delete[] name;
delete age;
}
void init(char* n, int a) {
name = n;
age = a;
}
void show(char* n, int a){
cout << "Name: " << name << "," << "age: " << age << "," << endl;
}
};
int main(void) {
Person *p = new Person;
p->init("Mary", 25);
p->show();
Person &p = pRef;
pRef->name = "Tom";
pRef->age = 18;
Person *p2 = new Person(pRef);
p->show();
p2->show();
system("PAUSE");
return 0;
}
The problem with your copy constructor is that it merely assigns p.name:
name = p.name // Now this and p hold a pointer to the same memory
Since both this and p now hold a pointer to the same memory location, whichever one destructs first will free the memory while the second one will be holding a pointer to a non-existent object. Subsequently using that pointer or deleting it will result in undefined behavior. The solution is to allocate a new array for name and copy the contents of p.name into that array, so that the memory isn't shared.
Likewise, your init function overwrites name, ignoring the fact that memory has been allocating (it is a memory leak) and also ignoring the fact that the string will later be destructed (even though the caller probably expects to own and free that string, itself). Also, I should point out that your show function takes a parameter "n", but uses "name", instead. Your show function probably shouldn't take any parameters (indeed, the way you call it implies that it doesn't), given that all the needed fields are already present in your class (or maybe you intended for that to be a freestanding function that takes the fields of the class?). You should take another look at your code for additional errors.
First of all, try to compile your code (it is usually a good idea to compile code before posting it on SO.) It contains several errors and compiler will show them. Second part will be to change the following:
p->init("Mary", 25);
to
{
std::string mary("Mary");
p->init(mary.c_str(), 25);
}
It should give you an error at runtime and it will give you a chance to find a problem in your implementation.