Everything seems to be copying fine, but when I call array2.print(), it shows segmentation fault. What am I doing wrong?
#include <iostream>
#include <initializer_list>
template <typename T>
class DynamicArray
{
private:
const int GROWTH_FACTOR = 2;
const int INITIAL_CAPACITY = 5;
T *m_array;
int m_capacity; // Capacity of the array
int m_size; // Number of added elements
public:
DynamicArray(std::initializer_list<T> elements)
: m_size(elements.size())
, m_capacity(elements.size() * 2)
{
m_array = new T[m_capacity];
std::copy(elements.begin(), elements.end(), m_array);
}
DynamicArray()
: m_size(0)
, m_capacity(INITIAL_CAPACITY)
{
m_array = new T[m_capacity];
}
~DynamicArray()
{
delete[] m_array;
}
DynamicArray(const DynamicArray& other)
: GROWTH_FACTOR(other.GROWTH_FACTOR)
, INITIAL_CAPACITY(other.INITIAL_CAPACITY)
, m_capacity(other.m_capacity)
, m_size(other.m_size)
{
T *m_array = new T[m_capacity];
std::copy(other.m_array, other.m_array + m_size, m_array);
}
int size()
{
return m_size;
}
int capacity()
{
return m_capacity;
}
void resize()
{
int new_capacity = m_capacity * GROWTH_FACTOR;
m_capacity = new_capacity;
T *temp = new T[new_capacity];
std::copy(m_array, m_array + m_capacity, temp);
delete[] m_array;
m_array = temp;
}
void deleteAt(int pos)
{
for (int i = pos; i < m_size - 1; i++)
{
(*this)[i] = (*this)[i + 1];
}
m_size--;
}
void insertAt(T value, int pos)
{
if (m_capacity == m_size)
{
resize();
}
for (int i = m_size - 1; i >= pos; i--)
{
(*this)[i + 1] = (*this)[i];
}
m_size++;
(*this)[pos] = value;
}
void append(T value)
{
insertAt(value, m_size);
}
void print() {
for (int i = 0; i < m_size; i++)
{
std::cout << (*this)[i] << ", ";
}
std::cout << std::endl;
}
T& operator[](int index)
{
if (index < 0 || index > m_size - 1)
{
throw std::invalid_argument("Index out of range!");
}
return m_array[index];
}
};
int main()
{
DynamicArray<int> array = { 1, 2, 3, 4 };
DynamicArray<int> array2 = array;
array2.print();
return 0;
}
The error is here
T *m_array = new T[m_capacity];
It should be
m_array = new T[m_capacity];
By declaring a new variable called m_array you hid the class member variable that you wanted to assign to. The technical name for this is shadowing, a good compiler would warn you about this.
You redeclare m_array in the cctor, which shadows the class member.
Related
i have this reSize function in my Array header
void reSize(int newsize) {
T* old = items;
size = newsize;
items = new T[newsize];
for (int i = 0;i < length;i++)
items[i] = old[i];
delete[]old;
}
and my main code:
struct User{
string name;
Array<int> data;
};
int main() {
Array<User> x(3);
x.get(0).name = "Kmal";
x.get(0).data.push_back(2); x.get(0).data.push_back(3);
x.reSize(10);
cout << x.get(0).data.get(0) <<endl;
return 0;
}
the problem is after resizing, my values that were stored in "data" variable are gone.
when i commented the code.
//delete[] old
in the reSize function
it worked fine...so i guess the problem is when i delete the pointer it deletes also the pointer inside the struct object which i don't want it to happen..
i don't want to comment the command becuz a leak in the memory will happen...how to fix this problem ?.
Update: My Array Class .
#include <iostream>
using namespace std;
template <class T>
class Array {
private :
T* items;
int size;
int length;
public :
Array() {
this->size = 0;
items = new T[this->size];
length = 0;
}
Array(int size) {
this->size = size;
items = new T[this->size];
length = 0;
}
int getsize() {
return this->size;
}
template <class T> void push_back(T x) {
if ((length+1) <= size) {
items[length] = x;
length++;
}
else {
this->reSize(size+1);
items[length] = x;
length++;
}
}
template <class T> void Insert(int index, T x) {
if (length + 1 <= size) {
for (int i = length;i > index;i--) {
items[i] = items[i - 1];
}
items[index] = x;
length++;
}
else {
this->reSize(size+1);
for (int i = length;i > index;i--) {
items[i] = items[i - 1];
}
items[length] = x;
length++;
}
}
template <class T> int Find(T x) {
int index = -1;
for (int i = 0;i < length;i++) {
if (items[i] ==x) {
index = i;
break;
}
}
return index;
}
void remove(int index) {
items[index] = "";
if(index+1 < length)
for (int i = index;i < length-1;i++) {
items[i] = items[i + 1];
items[i + 1] = "";
}
length--;
}
void reSize(int newsize) {
T* old = items;
size = newsize;
items = new T[newsize];
for (int i = 0;i < length;i++)
items[i] = old[i];
delete[]old;
}
void Merge(Array<T> x){
T* old = items; int oldlength = length;
items = new T[size + x.size];
size = size + x.size;
length += x.length;
for (int i = 0;i < length;i++) {
if(i< oldlength)
items[i] = old[i];
else
items[i] = x.items[i-oldlength];
}
delete[] old;
}
T& get(int index) {
return items[index];
}
}
struct User{
string name;
Array<int> data;
};
int main() {
Array<User> x(3);
// this line causes some problems
x.get(0).name = "Kmal";
x.get(0).data.push_back(2); x.get(0).data.push_back(3);
x.reSize(10);
cout << x.get(0).data.get(0) <<endl;
return 0;
}
In your code, declaring Array<User> x(3) declares an empty array with 3 elements that are preallocated. The length property of the array is 0. When the array is copied, length(0) elements are copied over into the resized storage. When you access the 0th element, it won't be copied on resize. What you actually need to do is call push_back() to add an element to the array so that length becomes 1 and the element is copied on resize.
Also, your array class is lacking a proper copy constructor and move constructor, which means copying it won't work at all. This means that User cannot be copied properly since it contains an array, which means that resizing an array of User won't work. You need to implement a copy constructor and copy assignment operator to be able to copy the array. You also need a destructor since, right now, the array is leaking memory when it goes out of scope.
My string-dynamic-array.cpp file
#include <iostream>
#include <string>
class DynamicArray
{
public:
DynamicArray()
: mCapacity(1), mNumberOfElements(0)
{
mArray = new std::string[mCapacity];
}
DynamicArray(int size)
: mCapacity(size), mNumberOfElements(0)
{
mArray = new std::string[mCapacity];
}
DynamicArray(const DynamicArray& array)
: mCapacity(array.getCapacity()), mNumberOfElements(array.length())
{
mArray = new std::string[mCapacity];
for (size_t i = 0; i < mCapacity; ++i)
{
mArray[i] = array.get(i);
}
}
~DynamicArray()
{
delete[] mArray;
}
void add(std::string element)
{
if (mNumberOfElements >= mCapacity)
{
expand();
}
mArray[mNumberOfElements++] = element;
}
std::string get(int index) const
{
if (index > mNumberOfElements)
{
std::string exception = std::to_string(index) + " index is out of bounds.";
std::cout << exception;
return std::string();
}
if (index < 0)
{
if (mNumberOfElements + index < 0)
{
std::string exception = std::to_string(index) + " index result in " + std::to_string(mNumberOfElements + index) + " which is out of bounds.\n";
std::cout << exception;
return std::string();
}
return mArray[mNumberOfElements + index];
}
return mArray[index];
}
int length() const
{
return mNumberOfElements;
}
int getCapacity() const
{
return mCapacity;
}
private:
int mCapacity;
int mNumberOfElements;
std::string* mArray;
void initialize(int from)
{
for (size_t i = from; i < mCapacity; ++i)
{
mArray[i] = std::string();
}
}
void expand()
{
mCapacity *= 2;
std::string* temporaryArray = new std::string[mCapacity];
for (size_t i = 0; i < mCapacity; ++i)
{
temporaryArray[i] = mArray[i];
}
delete[] mArray;
mArray = temporaryArray;
initialize(mNumberOfElements);
}
};
int main()
{
DynamicArray strings;
strings.add("Hello");
strings.add("World");
for (size_t i = 0; i < strings.length(); ++i)
{
std::cout << strings.get(i) << std::endl;
}
}
My output
$ clang++ tests/string-dynamic-array.cpp -o tests/string-dynamic-array && ./tests/string-dynamic-array
[1] 14950 segmentation fault (core dumped) ./tests/string-dynamic-array
I get a segmentation fault.
The issue as far as I've found is in the code where I expand the array, in the expand() function. I think it's in the for loop because the index of for loop is out of bounds of the original array.
I've tried this with int, it seems to work fine. How can I do this with strings?
As commented by UnholySheep.
I changed my expand function a bit so the loop only runs till the size of the old array.
Updated expand function:
void expand()
{
mCapacity *= 2;
std::string* temporaryArray = new std::string[mCapacity];
for (size_t i = 0; i < mNumberOfElements; ++i)
{
temporaryArray[i] = mArray[i];
}
delete[] mArray;
mArray = temporaryArray;
initialize(mNumberOfElements);
}
In “expand” method you have deleted mArray, then, you copied the temporaryArray to it, while as far as I know, mArray’s handle is not valid anymore. You need to pass temporaryArray‘s handle to mArray so you could use it as a new expanded array.
So I wrote this C++ Class for storing an Array:
#include<bits/stdc++.h>
using namespace std;
class Array
{
private:
int size;
int *A = new int[size];
int length;
public:
Array(int arr[],int sz = 10)
{
length = sz;
size = 10;
for(int i=0;i<length;i++)
A[i] = arr[i];
}
~Array()
{
delete []A;
}
void Display();
void Insert(int index, int x);
};
void Array::Display()
{//code}
void Array::Insert(int index, int x)
{//code}
int main()
{
int a[3] = {1,2,3};
Array arr(a, 3);
arr.Display();
arr.Insert(1,4);
arr.Display();
}
This works fine. But in the main() function:
int main()
{
int a[3] = {1,2,3};
Array arr(a, 3);
arr.Display();
}
I am passing the pointer to the array a in the Class constructor.
Is there a way to pass the array like this?
Array arr({1,2,3}, 3);
You probably need to use something like this. But please note this code is still not optimal and it is usually much better to use std::vector or in some cases std::array.
#include <initializer_list>
class Array
{
private:
int *m_data = nullptr;
int m_size = 0;
int m_capacity = 0;
public:
Array(int arr[], int sz = 10) {
m_size = sz;
m_capacity = sz;
m_data = new int[m_capacity];
for(int i=0; i < m_size; i++) {
m_data[i] = arr[i];
}
}
Array(const std::initializer_list<int> &il) {
m_size = il.size();
m_capacity = il.size();
m_data = new int[m_capacity];
auto it = il.begin();
for (int i = 0; i < m_size; ++i) {
m_data[i] = *it;
++it;
}
}
~Array() {
delete [] m_data;
}
int size() const { return m_size; }
bool empty() const { return m_size == 0; }
int& operator[](int id) { return m_data[id]; }
int operator[](int id) const { return m_data[id]; }
};
#include <cstdio> // for printf
int main() {
Array arr({1,2,3});
printf(" %i \n",arr.size());
return 0;
}
I've implemented a simple vector-like structure
It works well if i use vector<int> or vector<char>
but when i use <vector<vector<int>> it makes error
Is there are good implementation code about vector stl or problem in my code?
here is my code
class _vector {
private:
int _size;
int _capacity;
T* vc;
public:
_vector(int size = 1) {
_size = 0;
_capacity = size;
vc = new T[size];
}
~_vector() {
delete[] vc;
}
int size() { return _size; }
bool empty() { return !_size; }
void resize(int size) {
_capacity = size;
T* tmp = new T[size];
for (int i = 0; i < _size; i++) tmp[i] = vc[i];
delete[] vc;
vc = tmp;
}
void clear() {
delete[] vc;
_capacity = 1;
_size = 0;
vc = new T[_capacity];
}
void push_back(T val) {
if (_size == _capacity) resize(2 * _capacity);
vc[_size++] = val;
}
void pop_back() {
if (_size == 0) return;
vc[--_size] = 0;
}
T& operator[](int i) const { return vc[i]; }
_vector<T>& operator=(_vector<T> &tmp) {
_capacity = tmp._capacity;
_size = tmp._size;
delete[] vc;
vc = new T[_capacity];
for (int i = 0; i < _size; i++) vc[i] = tmp[i];
return *this;
}
Your implementation is not following the Rule of 3, as it is missing a copy constructor, and a proper copy assignment operator (which can be implemented utilizing the copy constructor). And in C++11 and later, the Rule of 5, by adding a move constructor and a move assignment operator.
Also, your implementation does not work correctly with non-trivial types that have constructors/destructors defined, such as when T is another _vector type, or any other type that has pointers/resources allocated inside of it. So, your class needs to construct new objects when adding elements to the array, using placement-new, and destruct objects when removing elements from the array, by directly calling their destructors.
Try something more like this instead:
template <typename T>
class _vector {
public:
typedef unsigned int size_type;
typedef T value_type;
private:
size_type _size;
size_type _capacity;
value_type* vc;
public:
_vector(size_type initalcap = 0) : _size(0), _capacity(0), vc(0) {
reserve(initialcap);
}
_vector(const _vector<T> &src) : _size(0), _capacity(0), vc(0) {
reserve(src._capacity);
for(size_type i = 0; i < src._size; ++i) {
new(vc[i]) value_type(src.vc[i]);
}
_size = src._size;
}
// C++11 and later only...
_vector(_vector<T> &&src) : _size(src._size), _capacity(src._capacity), vc(src._vc) {
src._size = 0;
src._capacity = 0;
src.vc = 0;
}
~_vector() {
clear();
delete[] reinterpret_cast<char*>(vc);
}
size_type size() const { return _size; }
size_type capacity() const { return _capacity; }
bool empty() const { return !_size; }
void reserve(size_type newcap) {
if (newcap <= _capacity) return;
value_type* tmp = reinterpret_cast<value_type*>(new char[sizeof(value_type) * newcap]);
for (size_type i = 0; i < _size; ++i) {
new(tmp[i]) value_type(vc[i]);
}
delete[] reinterpret_cast<char*>(vc);
vc = tmp;
_capacity = newcap;
}
void resize(size_type newsize) {
if (newsize < _size) {
for(size_type i = _size; i-- > newsize; ) {
vc[i].~value_type();
}
_size = newsize;
}
else if (newsize > _size) {
reserve(newsize);
for (size_type i = _size; i < newsize; ++i) {
new(vc[i]) value_type();
}
_size = newsize;
}
}
void clear() {
resize(0);
}
void push_back(const T &val) {
if (_size == _capacity) reserve(2 * _capacity);
new(vc[_size]) value_type(val);
++_size;
}
void pop_back() {
if (_size) {
vc[--_size].~value_type();
}
}
value_type& operator[](size_type i) { return vc[i]; }
const value_type& operator[](size_type i) const { return vc[i]; }
_vector<T>& operator=(const _vector<T> &rhs) {
if (&rhs != this) {
_vector<T> tmp(rhs);
std::swap(tmp.vc, vc);
std::swap(tmp._size, _size);
std::swap(tmp._capacity, _capacity);
}
return *this;
}
// C++11 and later only...
_vector<T>& operator=(_vector<T> &&rhs) {
_vector<T> tmp(std::move(rhs));
std::swap(tmp.vc, vc);
std::swap(tmp._size, _size);
std::swap(tmp._capacity, _capacity);
return *this;
}
};
I have a problem with my code, and I don't understand what is wrong with it.
This is the were the problem occurs in the code:
void Safe_Array::resize(unsigned new_capacity)
{
score += sizeof(int)*(new_capacity - m_capacity);
if (m_capacity < new_capacity)
{
int old_len = m_capacity - 1;
Safe_Array temp(*this);
if (m_data)
delete[] m_data;
m_data = new int[sizeof(int)*new_capacity]; // new allocation
m_capacity = new_capacity;
for (int i = 0; i < old_len + 1; i++)
m_data[i] = temp.m_data[i];
for (; old_len < new_capacity; old_len++)
m_data[old_len] = 0;
}
else // here we need to shorten the array
{
Safe_Array temp(*this);
if (m_data)
delete[] m_data;
m_data = new int[sizeof(int)*new_capacity]; // new allocation
m_capacity = new_capacity;
for (int i = 0; i < new_capacity; i++)
m_data[i] = temp.m_data[i];
}
}
I encounter the error when I try to delete m_data.
The purpose of this function:
first I have created an object that m_data is its array, resize is a function that will as it say "resize" this field of the object.
Here is the Header file:
class Safe_Array
{
public:
Safe_Array(unsigned capacity = 0, const int max_tries = 3);
Safe_Array(const Safe_Array&);
~Safe_Array();
void show(void) const;
unsigned get_capacity() const;
bool insert(int, unsigned);
bool get(unsigned index, int &value) const;
bool search(int value, unsigned &index) const;
Safe_Array& assign(const Safe_Array&);
void resize(unsigned);
void sort();
static unsigned get_score();
friend int compare(const Safe_Array& a, const Safe_Array& b);
Safe_Array& create(unsigned index1, unsigned index2);
private:
int *m_data;
unsigned m_capacity;
static unsigned score;
const int m_max_tries;
unsigned int counter;
};
Here is the cpp file of the function. (including distractor, contractor, copy contractor, and the function resize):
Safe_Array::Safe_Array(unsigned capacity, int max_tries) :
m_max_tries(max_tries), m_capacity(0), m_data(NULL), counter(0)
{
m_capacity = capacity;
//counter = 0; // when created counter = 0
m_data = new int[capacity];
memset(m_data, 0, m_capacity*sizeof(int));
score += sizeof(Safe_Array) + sizeof(int)*m_capacity;
}
Safe_Array::Safe_Array(const Safe_Array& org_obj) :
m_max_tries(org_obj.m_max_tries), m_capacity(org_obj.m_capacity), counter(0) // copy constractor
{
m_data = new int[m_capacity];
memcpy(m_data, org_obj.m_data, m_capacity * sizeof(int)); // copy sizeof(int)*4 -> int is 4 bytes & memcpy copies bytes
score += sizeof(Safe_Array) + sizeof(int)*m_capacity;
}
Safe_Array::~Safe_Array() // distractor
{
if (m_data) // check if object exists
delete[] m_data;
score -= sizeof(Safe_Array) + sizeof(int)*m_capacity; // uptade score
}
probably Safe_Array temp(*this); do not copy (deeply) m_data, so after the delete you look at a freed memory.
Moving the delete later :
if (m_data) {
int * old = m_data;
m_data = new int[sizeof(int)*new_capacity]; // new allocation
m_capacity = new_capacity;
for (int i = 0; i < old_len + 1; i++)
m_data[i] = old[i];
delete[] old;
}
To clone the current instance just to (hope to) save a member of it is a bad way.