Can anybody help me to do my own Vector class? - c++

I have problem only with the push_back function, the compiler said:
CRT detected that the application wrote to memory after end of heap buffer
I want to make a push_back function, that adds a new element to the vector's end.
#pragma once
#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstdlib>
class tomb {
private:
double *adat;
int szam;
public:
tomb(){
adat = NULL;
szam = 0;
}
int meret()const {
return szam;
}
~tomb() {
delete[] adat;
}
double & operator[](int n) {
return adat[n];
}
const double & operator[](int n)const {
return adat[n];
}
void push_back(const double &a) {
double *tmp;
int pos = szam + 1;
tmp = new double[szam+1];
for (int i = 0; i < szam; i++)
{
tmp[i] = adat[i];
}
tmp[pos] = a;
delete[] adat;
adat = tmp;
++szam;
}
void Kiir()const {
for (int i = 0; i < szam; i++)
{
std::cout << adat[i] << "\n";
}
}
};

pos should be szam not szam+1. You are willing to insert at the last position, which in 0-based indexing is n-1.

The problem is in this line:
tmp[pos] = a;
Since pos is initialized to szam + 1, that is equivalent to:
tmp[szam + 1] = a;
which is one out of the array limit.
The solution is to get rid of pos altogether and just do:
tmp[szam] = a;
BTW, your class is using the default copy constructor and assignment operator, and those will not work properly. You should really do something about that.

Related

C++ class objects copy constructor and operator=

I'm currently building a library In C++. I have met this problem few days ago and I'm unable to fix it. I have shorten the code so it can be seen easier.
Below is my code:
class String
{
private:
mutable char* v;
mutable int l = 0;
public:
String()
{
l++;
v = new char[1];
*v = '\0';
}
String(const char* value)
{
int length = 0;
while (value[length])
length++;
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
}
String(const String& value)
{
int length = value.len();
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
}
int len() const
{
return l - 1;
}
char* val() const
{
return v;
}
char* operator=(const char* value) const
{
delete[] v;
int length = 0;
while (value[length])
length++;
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
return v;
}
char* operator=(const String& value) const
{
delete[] v;
int length = value.len();
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
return v;
}
char operator[](const int& index) const
{
return v[index];
}
};
class StringArray
{
private:
union ArrayDef
{
public:
mutable String stringV;
mutable int intV;
ArrayDef()
{
}
ArrayDef(const String& value)
: stringV(value)
{
}
ArrayDef(const int& value)
: intV(value)
{
}
ArrayDef(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
}
String operator=(const String& value) const
{
stringV = value;
return stringV;
}
int operator=(const int& value) const
{
intV = value;
return intV;
}
ArrayDef operator=(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
return *this;
}
};
mutable ArrayDef* arrdef;
mutable int arrLen = 0;
public:
StringArray()
{
}
void add(const ArrayDef& value) const
{
ArrayDef temp[arrLen + 1];
for (int i = 0; i < arrLen; i++)
temp[i] = arrdef[i];
temp[arrLen] = value;
arrLen++;
delete[] arrdef;
arrdef = new ArrayDef[arrLen];
for (int i = 0; i < arrLen; i++)
arrdef[i] = temp[i];
}
int len() const
{
return arrLen;
}
ArrayDef val(const int& index) const
{
return arrdef[index];
}
};
And my driver code:
#include <iostream>
int main()
{
StringArray arr;
arr.add(String("Hello"));
arr.add(String("World"));
std::cout << "Length of the array: " << arr.len() << std::endl;
int indexOfString = 1;
int indexOfCharacter = 2;
char s = arr.val(indexOfString).stringV[indexOfCharacter];
std::cout << "arr[" << indexOfString << "][" << indexOfCharacter << "]: " << s << std::endl;
}
I have created two class, that is, String and StringArray class.
For String class, I need to always add a null character after the char pointer array for safety issue.
For StringArray class, I uses union because it's actually an array for multiple types.
It can be successfully compiled but it output some random character and it is different every time I run it.
Any answers will be appreciated, and please tell me why and how it don't works. Thank you.
From,
HaiQin.
This code is just a collection of antipatters that makes it difficult to study. What is the reason of making the internal data mutable? Why do you need to play with length and l where sometimes it is the length of the string, sometimes it is the size of array? The operator operator= returns char* which is a bad practice. Using const int& index as a parameter is a strange choice. You allocate arrays multiple times but you have no destructor that frees the memory.
Here your assignment operator returns a value, not reference!
ArrayDef operator=(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
return *this;
}
Next comes even more dangerous practice:
// Recollect that this is a union
ArrayDef(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
}
You are assigning both fields of the union at the same time! Did you mean struct?
Try to fix that. Start with changing union to structure.
One of the things that certainly will not work is the ArrayDef copy constructor and operator=(const ArrayDef & value). This is because you may only use the active value in the union, not both at the same time. This is usually solved by using a tagged union. Is there a reason you cannot use the Standard Template Library?
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> arr;
arr.push_back(std::string("Hello"));
arr.push_back(std::string("World"));
std::cout << "Length of the array: " << arr.size() << std::endl;
constexpr int indexOfString = 1; // second string - starting from 0!
constexpr int indexOfCharacter = 2; // third character
char s = arr.at(indexOfString).c_str()[indexOfCharacter]; // using interfaces closest to the original
std::cout << "arr[" << indexOfString << "][" << indexOfCharacter << "]: " << s << std::endl;
}

C++ Bubble sort dynamically allocated array

I wrote a bubble sorting algorithm which sorts a dynamically allocated array using string comparison.
Here is my code:
void AddressBook::bubble_sort_address_book(){
bool swapped = true;
while(swapped){
swapped = false;
for(int i = 0; i < noOfEmployees; i++){
if(employees[i].combined_name() > employees[i+1].combined_name()){
Employee temp_employee = employees[i+1];
employees[i+1] = employees[i];
employees[i] = temp_employee;
}
}
}
}
My problem is pretty obvious, yet I can not seem to figure out how to solve it: The code sometimes fails on the line (in an undefined manner) :
Employee temp_employee = employees[i+1]
Its pretty obvious because if i is equal to the end of the array, accessing memory with i+1 results in undefined behaviour. However, if I stop the for loop with noOfEmployees-1, this does not happen but the first element is never sorted (obviously).
How can I implement bubble sort properly? It seems as such a trivial task. Am I missing something?
The following simplified version in pure C works fine:
int employees[10]= {3,1,7,6,9,7,1,0,2,6};
int noOfEmployees= 10;
void bubble_sort_address_book(void){
bool swapped = true;
int i;
while(swapped){
swapped = false;
for(i = 0; i < noOfEmployees-1; i++){
if(employees[i] > employees[i+1]){
int temp_employee = employees[i+1];
employees[i+1] = employees[i];
employees[i] = temp_employee;
swapped= true;
}
}
}
}
int main()
{
int i;
bubble_sort_address_book();
for (i=0; i<noOfEmployees; i++) {
printf("emp %d= %d\n", i, employees[i]);
}
return 0;
}
As you request, the function of variable swapped is to indicate that following a complete pass through the array no swap occurred and so it indicates the array is now sorted.
You can use an explicit bound on the outer loop.
You should also split things out into smaller functions.
bool operator <(Employee const & lhs, Employee const & rhs) {
return lhs.combined_name() < rhs.combined_name();
}
// a.k.a. std::swap
void swap(Employee & lhs, Employee & rhs) {
Employee temp(static_cast<Employee&&>(lhs)); // a.k.a. std::move
lhs = static_cast<Employee&&>(rhs);
rhs = static_cast<Employee&&>(temp);
}
void bubble_sort_impl(Employee * begin, Employee * end) {
for (; end != begin; --end) {
for (Employee * it = begin; it+1 != end; ++it) {
if (*(it+1) < *it) {
swap(*it, *(it+1));
}
}
}
}
// do we really need "bubble_" or "_address_book" in this name?
void AddressBook::bubble_sort_address_book() {
bubble_sort_impl(employees, employees + noOfEmployees);
}
another solution:
#include <iostream>
#include <vector>
using namespace std;
int employees[10] = { 3,1,7,6,9,7,1,0,2,6 };
void bubble_sort_address_book(void) {
bool swapped = true;
int i;
int noOfEmployees = 10;
while (swapped) {
swapped = false;
for (i = 1; i <= noOfEmployees ; i++) {
if (employees[i] > employees[i - 1]) {
int temp_employee = employees[i - 1];
employees[i - 1] = employees[i];
employees[i] = temp_employee;
swapped = true;
}
}
}
}
int main()
{
int i;
int noOfEmployees = 10;
bubble_sort_address_book();
for (i = 0; i<noOfEmployees; i++) {
printf("emp %d= %d\n", i, employees[i]);
}
return 0;
}

Program triggering a breakpoint

Hey I'm having trouble figuring out what is causing my program to trigger a breakpoint. For school I had to write a class using templates that mimics a java array list, but in c++. My code seems to work when I only use the push method that I have written more than twice in a test. If I try pushing more than two values onto the arraylist, it starts triggering breakpoints.
Here's my code:
HeaderFile:
Arraylist.h
#include <string>
using namespace std;
template<class t>
class ArrayList {
public:
ArrayList();
void push_back(t m);
void erase(t m);
int size();
string toString();
t& operator[](unsigned int i);
private:
int currentIndex;
int sizeOfArray;
t *p;
int currentindex;
};
ArrayList.cpp
#include "ArrayList.h"
#include <iostream>
using namespace std;
template<class t>
ArrayList<t>::ArrayList() {
p = new t[1];
sizeOfArray = 1;
currentIndex = 0;
p[currentIndex] = 0;
currentIndex++;
}
template<class t>
int ArrayList<t>::size() {
return sizeOfArray;
}
template<class t>
void ArrayList<t>::erase(t m) {
int location = 0;
for (int i = 0; i < currentIndex; i++) {
if (p[i] == m) {
location = i;
}
}
for (int i = location; i < currentIndex - 1; i++) {
p[i] = p[i + 1];
}
currentIndex--;
}
template<class t>
void ArrayList<t>::push_back(t m) {
if (currentIndex < sizeOfArray-1) {
t *temp = new t[sizeOfArray + 1];
sizeOfArray++;
for(int i=0;i<sizeOfArray-1;i++){
temp[i] = p[i];
}
temp[currentIndex] = m;
currentIndex++;
sizeOfArray++;
delete [] p;
t *p = new t[sizeOfArray];
p = temp;
delete [] temp;
}
else {
p[currentIndex] = m;
currentIndex++;
}
}
template<class t>
t& ArrayList<t>::operator[](unsigned int i) {
return p[i];
}
template<class t>
string ArrayList<t>::toString() {
string output = "";
for (int i = 0; i < sizeof(p); i++) {
output += to_string(p[i]);
}
return output;
}
Source.cpp (just using it as a scratchpad for testing)
#include "ArrayList.cpp"
#include <iostream>
using namespace std;
int main()
{
ArrayList<double> list = ArrayList<double>();
list.push_back(1.0);
list.push_back(2.0);
list.push_back(3.0);
//list.push_back(4.0);
cout << list.toString();
cin.get();
return 0;
}
I believe that the problem has something to do with me somehow going out of bounds with one of my array's, but I can't seem to figure it out (perhaps I've just been staring at this assignment for to long). Any help, or suggestions would be much appreciated as always.

C++: Passing a (pointer to an?) array of objects by reference

I'm new to C++, and I'm having significant trouble with creating an array of objects using a pass by pointer and reference. This is not the actual code; it's an example of what the code essentially does.
#include <iostream>
class MyClass
{
public:
MyClass();
static int doStuff(MyClass *&classArray);
void print_number();
private:
int number;
};
MyClass::MyClass()
{
}
int MyClass::doStuff(MyClass *&classArray)
{
int i = 0;
for (i = 0; i < 10; i++) {
*classArray[i].number = i;
}
return i;
}
void MyClass::print_number()
{
std::cout << number << "\n";
}
int main(void)
{
MyClass *test = nullptr;
int p = MyClass::doStuff(test);
std::cout << p << '\n';
for (int i = 0; i < 10; i++) {
test[i].print_number();
}
return 0;
}
When compiled, this gives a segmentation fault.
This is how you do it (don't forget do delete classArray with delete[] at the end of your program or destructor:
new operator has to have default constructor, if you want to use non-default it is easier to create copy constructor, then a temporary object and copy.
#include <iostream>
class MyClass
{
public:
MyClass();
MyClass(int x, int y);
MyClass(MyClass &OldClass);
static int doStuff(MyClass *&classArray, int Size, int x, int y);
void print_number();
private:
int number, x, y;
};
MyClass::MyClass()
{
number = 0;
x = 0;
y = 0;
}
MyClass::MyClass(int x, int y)
{
number = 0;
this->x = x;
this->y = y;
}
MyClass::MyClass(MyClass &OldClass)
{
this->number = OldClass.number;
this->x = OldClass.x;
this->y = OldClass.y;
}
int MyClass::doStuff(MyClass *&classArray, int Size, int x, int y)
{
if (Size > 0)
{
classArray = new MyClass[Size];
for (int i = 0; i < Size; i++)
{
classArray[i] = MyClass(x, y);
classArray[i].number = i;
}
return Size;
}
else
return 0;
}
void MyClass::print_number()
{
std::cout << number << " " << x << " " << y << "\n";
}
int main(void)
{
MyClass *test = nullptr;
int p = MyClass::doStuff(test, 10, 5, 6);
std::cout << p << '\n';
for (int i = 0; i < p; i++) {
test[i].print_number();
}
delete[] test;
std::cin.get();
return 0;
}
It is not working because you need to allocate the array, as the function is trying to access elements of an array which has yet not been initialized to hold that amount of elements. You can do this by
MyClass *test = new MyClass[array_size];
Or
MyClass test[array_size];
Or by using a resizable container such as std::vector, and changing the function parameters accordingly
*classArray[i].number = i;
You called doStuff with a null pointer, so classArray is null and is not an array. Dereferencing a null pointer results in undefined behavior and on most implementations you'll usually get a crash.
You're also dereferencing something that's not a pointer so this code will not even compile. The error I get is:
main.cpp:23:9: error: indirection requires pointer operand ('int' invalid)
*classArray[i].number = i;
^~~~~~~~~~~~~~~~~~~~~
Presumably this is just because, as you say, the code you're showing is not your real code and classArray[i].number corresponds to a pointer in your real code. But I thought I'd point this out anyway, just in case.
Given the context of your code, here's a working example of your code:
#include <iostream>
class MyClass
{
public:
MyClass() {}
static int doStuff(MyClass*& classArray, size_t sz)
{
int i = 0;
for (; i < sz; i++) {
classArray[i].number = i;
}
// not sure what you want here, but this will return sz+1 if sz>0
return i;
}
void print_number()
{
std::cout << this->number << std::endl;
}
private:
int number;
};
int main(void)
{
MyClass* test = new MyClass[10];
int p = MyClass::doStuff(test, 10);
std::cout << p << '\n';
for (int i = 0; i < 10; i++) {
test[i].print_number();
}
delete[] test;
return 0;
}
Though as others have pointed out, you are using C++, while it's a great exercise in understand how to pass pointers and arrays around, you might find the STL and C++stdlib contain a lot of these types of idioms in an 'easier to understand context'.
Here's your code with some C++ STL:
#include <iostream>
#include <vector>
class MyClass
{
public:
MyClass() {}
MyClass(int i) : number(i) {}
static int doStuff(std::vector<MyClass>& classArray, size_t sz)
{
int i = 0;
for (; i < sz; i++) {
classArray.push_back(MyClass(i));
}
// not sure what you want here, but this will return sz+1 if sz>0
return i;
}
void print_number()
{
std::cout << this->number << std::endl;
}
private:
int number;
};
int main(void)
{
std::vector<MyClass> test;
int p = MyClass::doStuff(test, 10);
std::cout << test.size() << '\n';
// can use iterators here if you want
std::vector<MyClass>::iterator itr = test.begin();
for (; itr != test.end(); itr++) {
itr->print_number();
}
return 0;
}
Hope that can help.

C++ program crashes down

I'm doing a project with C++ and my program keeps crashing down when I try to run it...here is my code (two files: main.cpp and PlacementHead.cpp):
main.cpp:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <climits>
#include "PlacementHead.h"
// Main
int main (int argc, char * const argv[]) {
PlacementHead h1(4,2,1,"aabcbbca");
PlacementHead h2(4,2,1,"babcabca");
return 0;
}
PlacementHead.cpp:
#include "PlacementHead.h"
#include <string>
#include <iostream>
#include <string.h>
PlacementHead::PlacementHead(int width, int height, int gap, char* s) {
width_ = width;
height_ = height;
gap_ = gap;
size_ = width*height;
set_ = new char[size_];
from_ = new int[size_];
original_ = new char[size_];
strcpy(set_,s);
strcpy(original_,s);
}
PlacementHead::~PlacementHead() {
}
int PlacementHead::getSize() { return size_; }
int PlacementHead::getHeight() { return height_; }
int PlacementHead::getWidth() { return width_; }
int PlacementHead::getGap() { return gap_; }
char PlacementHead::getNozzle(int i) {
return set_[i-1];
}
void PlacementHead::setNozzle(int i, char c) {
set_[i-1] = c;
}
void PlacementHead::markNozzle(int i, int bankPos) {
set_[i-1] = ' ';
from_[i-1] = bankPos;
}
int PlacementHead::getNextUnmarkedPos() {
for (int i=0; i<size_; i++) {
if (set_[i]!=' ') {
return i+1;
}
}
return 0;
}
int PlacementHead::getBankPos(int i) {
return from_[i-1];
}
void PlacementHead::reset() {
//for (int i=0; i<size_; i++) {
// set_[i] = original_[i];
//}
strcpy(set_,original_);
}
void PlacementHead::print() {
std::cout << "placementhead:\n";
for (int h=height_; h>0; h--) {
for (int w=width_; w>0; w--) {
int i = ((h-1)*width_)+w;
std::cout << getNozzle(i);
}
std::cout << "\n";
}
}
If I try to run the main.cpp, I get this:
Once I got this also (I don't get this every time, which bugs me...):
Now here is also one thing to take into account: If I comment out the second line where PlacementHead h2-object is created the code runs okay, but IF I create more than one PlacementHead-objects the program crashes again...
Any advices what might be causing this?
Thank you for any help!! =)
P.S.
My platform is Windows 7, Codeblocks 12.11 and GNU GCC Compiler
UPDATE:
In case you couldn't see the text on the second picture here it is:
You should
increase size_ by +1 too avoid buffer overrun (or, use std::vector instead, see below)
disable copy construction/assignment
add a proper destructor
use initialization lists
check the order in which members are declared (since this is also the order in which members are initialized!)
remove the default constructor, since it doesn't initialize a single member
include <cstring> instead of <string.h> on modern compilers (so you get namespaces C standard library functions)
Consider using std::vector instead of manual arrays. This will save you much trouble. Think of how you are going to get your constructor exception safe?
Here is a sample fixing all of the above:
#include <iostream>
#include <vector>
#include <cstring>
struct PlacementHead {
int width_, height_, gap_;
size_t size_;
std::vector<char> set_, original_;
std::vector<int> from_;
PlacementHead(int width, int height, int gap, const char* s) :
width_(width),
height_(height),
gap_(gap),
size_(width * height),
set_(s, s + std::min(strlen(s), size_)),
original_(set_),
from_(size_)
{
set_.resize(size_);
original_.resize(size_);
}
size_t getSize() { return size_; }
int getHeight() { return height_; }
int getWidth() { return width_; }
int getGap() { return gap_; }
char getNozzle(int i) { return set_[i - 1]; }
void setNozzle(int i, char c) { set_[i - 1] = c; }
void markNozzle(int i, int bankPos) {
set_[i - 1] = ' ';
from_[i - 1] = bankPos;
}
int getNextUnmarkedPos() {
for(unsigned i = 0; i < size_; i++) {
if(set_[i] != ' ') {
return i + 1;
}
}
return 0;
}
int getBankPos(int i) { return from_[i - 1]; }
void reset() {
//for (int i=0; i<size_; i++) {
// set_[i] = original_[i];
//}
set_ = original_;
}
void print() {
std::cout << "placementhead:\n";
for(int h = height_; h > 0; h--) {
for(int w = width_; w > 0; w--) {
int i = ((h - 1) * width_) + w;
std::cout << getNozzle(i);
}
std::cout << "\n";
}
}
};
// Main
int main (int argc, char * const argv[]) {
PlacementHead h1(4,2,1,"aabcbbca");
PlacementHead h2(4,2,1,"babcabca");
return 0;
}
size_ = width*height; should be size_ = (width*height)+1; so the string can be null terminated. Currently you are writing to unallocated memory causing undefined behaviour
You have an off-by-one error in your constructor, as the strings you try to copy are not 8 characters, they are 9. The reason is that all string literals are also containing an extra special string termination character.
If you're using strings in C++, use std::string, it will help you tremendously with problems like these.