I need to implement a dynamic array by myself to use it in a simple memory manager.
struct Block {
int* offset;
bool used;
int size;
Block(int* off=NULL, bool isUsed=false, int sz=0): offset(off), used(isUsed), size(sz) {}
Block(const Block& b): offset(b.offset), used(b.used), size(b.size) {}
};
class BlockList {
Block* first;
int size;
public:
BlockList(): first(NULL), size(0) {}
void PushBack(const Block&);
void DeleteBack();
void PushMiddle(int, const Block&);
void DeleteMiddle(int);
int Size() const { return size; }
void show();
Block& operator[](int);
Block* GetElem(int);
void SetElem(int, const Block&);
~BlockList();
};
I need to overload operator[].
Block& BlockList::operator\[\](int index) {
try {
if (index >= size)
throw out_of_range("index out of range");
else
return (first[sizeof(Block)*index]);
}
catch(exception& e) {
cerr << e.what() << endl;
}
}
void BlockList::PushBack(const Block& b) {
if(!size)
first = new Block(b);
else {
Block* temp = new Block[size + 1];
int i = 0;
for (i = 0; i < size; i++)
temp[sizeof(Block)*i] = this->operator[](i);
delete []first;
temp += sizeof(Block);
temp->offset = b.offset;
temp->size = b.size;
temp->used = b.used;
first = temp;
}
size++;
}
When I use PushBack to push the first element, it works OK, but when it comes to the second, third, ..., the program didn't crash, but it just shows results I didn`t expect to see.
Here is how I get the contents of my array:
void BlockList::show() {
for (int i = 0; i < size; i++) {
Block current(operator[](i));
cout << "off: " << current.offset << " size: " << current.size << endl;
}
}
first is a Block pointer so you only need to pass in index.
Block* first;
...
first[0] //returns the first element
first[1] //returns the second element
In your example you are passing in too high of an index value when indexing first because you're using sizeof inside.
Corrected code:
Block& BlockList::operator[](int index) {
try {
if (index >= size)
throw out_of_range("index out of range");
else
return (first[index]);//<--- fix was here
}
catch(exception& e) {
cerr << e.what() << endl;
}
}
An array knows how big its elements are, so you don't have to do the math with sizeof(Block). Just use i as the index.
On a related note, the C++ FAQ Lite has a great section on operator overloading that covers all kinds of useful stuff.
Related
The error pointed out was at the end just before the };
I don't even see any function overloading or any mismatching parameters.
This is simply a queue data structure that I was trying to implement. But unfortunately, I got these compiler errors. I am sharing the whole code so that easily one can help, since neither I have any function overloaded, not even the constructor nor I have used mismatched parameter. I guess image will help out to see the error.
template<class T>
class Queue {
private:
T* box;
int front;
int rear;
int number_Of_Elements;
int capacity;
public:
Queue(int cap = 0) {
capacity = cap;
front = rear = 0;
number_Of_Elements = 0;
}
bool Empty() {
return size == 0;
}
int next(int i) {
return ((i + 1) % capacity);
}
int previous(int i) {
return ((i + (capacity - 1)) % capacity);
}
int get_Number_Of_Elements() {
return number_Of_Elements;
}
void double_Box() {
T* temp = new T[capacity * 2];
for (int i = 0; i < size; i++) {
temp[i] = box[i];
}
front = 0;
rear = number_Of_Elements;
delete[] box;
box = temp;
}
const T& peek() {
T a = box[front];
front = next(front);
return a;
}
void printQueue() {
cout << "Front is at : " << front << endl;
cout << "Rear is at : " << rear << endl;
for (int i = 0; i < number_Of_Elements; i++) {
cout << "box[" << i << "]" << " : " << box[i] << endl;
}
cout << "------------------------" << endl;
}
void Enqueue(const T& data);
const T& Dequeue();
~Queue() {
delete[] box;
}
// error is exactly here -> };
};
Your problem is with size. You haven't declared it.
I think the compiler tries to use some global function called size instead but it fails.
After declaring the capacity member var, add
size_t size;
Demo
The answer is, there were issues, like some of the variables were not even initialized but they were being used, and the memory calculation errors were there. Like a pointer pointing somewhere in memory that actually does not exist.
I made a dynamic array with template. The problem is that when I don't keep there pointers (for example: Tab<string> da;) my destructor doesn't have to clear it and throws error caused by delete arr[i];. My question is if I can put some if condition(in which I would put clear() method) which would tell me if my array keeps pointers. In the simplest way I can use clear() in main when I keeps there pointers, but my teacher wants me to make it like I wrote above.
I tried using is_pointer, but it doesn't work or I use it wrong.
Any suggestions?
#ifndef TABLICA_H
#define TABLICA_H
#include <iostream>
#include <type_traits>
using namespace std;
template<class T>
class Tab
{
public:
int size = 0;
int max_size = 1;
T* arr;
bool isDynamic = false;
Tab()
{
arr = new T[max_size];
}
~Tab()
{
clear();
delete[] arr;
}
void check_size()
{
if (size == max_size)
{
max_size = max_size * 2;
T* arr2 = new T[max_size];
for (int i = 0; i < size; i++)
{
arr2[i] = arr[i];
}
delete[] arr;
arr = arr2;
}
}
void push_back(const T& value)
{
check_size();
arr[size] = value;
size++;
}
T return_by_index(int index)
{
if (index<0 || index > size)
{
return NULL;
}
return arr[index];
}
bool replace(int index, const T& value)
{
if (index<0 || index > size)
{
return false;
}
arr[index] = value;
return true;
}
void print(int number)
{
cout << "Rozmiar obecny: " << size << endl;
cout << "Rozmiar maksymalny: " << max_size << endl;
cout << "Adres tablicy: " << arr << endl;
cout << "Kilka poczatkowych elementow tablicy " << "(" << number << ")" << endl;
for (int i = 0; i < number; i++)
{
cout << *arr[i] << endl;
}
}
void clear()
{
for (int i = 0; i < size; i++)
{
delete arr[i];
}
}
};
#endif
//Source:
#include <iostream>
struct object
{
int field1;
char field2;
object()
{
field1 = rand() % 10001;
field2 = rand() % 26 + 'A';
}
};
ostream& operator<<(ostream& out, const object& o)
{
return out << o.field1 << " " << o.field2;
}
int main()
{
Tab < object* >* da = new Tab < object* >();
delete da;
system("PAUSE");
return 0;
This is a Stack class based on a dynamic array of struct for Depth First Search (DFS). The program is not able to run whenever it encounters the function, push(), which shows that the array is not successfully initialized in the constructor.
I have tried to look for the error and even changing the dynamic array of struct into parallel arrays but it still does not work. I apologize if the problem seems to be too simple to be solved as I do not have a strong foundation in C++.
#include <iostream>
#include <iomanip>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
struct Value
{
int row; // row number of position
int col; // column number of position
//operator int() const { return row; }
};
class ArrayStack
{
public:
int top;
Value* array;
ArrayStack();
bool isEmpty();
bool isFull();
void push(int r, int c);
void pop();
int poprowvalue(int value);
int popcolvalue(int value);
int peekrow(int pos);
int peekcol(int pos);
int count();
void change(int pos, int value1, int value2);
void display();
void resize();
private:
int size;
};
ArrayStack::ArrayStack()
{
//Initialize all variablies
top = -1;
size = 10;
Value * array = new Value[size];
for (int i = 0; i < size; i++)
{
array[i].row = 0;
array[i].col = 0;
}
}
bool ArrayStack::isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool ArrayStack::isFull()
{
if (top == size - 1)
return true;
else
return false;
}
void ArrayStack::resize()
{
if (isFull())
size *= 2;
else if (top == size / 4)
size /= 2;
}
void ArrayStack::push(int r, int c)
{
if (isEmpty() == false)
resize();
array[top + 1].row = r;
array[top + 1].col = c;
top++;
}
void ArrayStack::pop()
{
int value;
if (isEmpty())
{
cout << "Stack underflow" << endl;
}
else
{
poprowvalue(array[top].row);
popcolvalue(array[top].col);
array[top].row = 0;
array[top].col = 0;
top--;
}
}
int ArrayStack::poprowvalue(int v)
{
return v;
}
int ArrayStack::popcolvalue(int v)
{
return v;
}
int ArrayStack::peekrow(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].row;
}
int ArrayStack::peekcol(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].col;
}
int ArrayStack::count()
{
return (top + 1);
}
void ArrayStack::change(int pos, int value1, int value2)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
{
array[pos].row = value1;
array[pos].col = value2;
}
}
void ArrayStack::display()
{
for (int i = size - 1; i > -1; i--)
{
cout << array[i].row << " " << array[i].col << endl;
}
}
#endif
I expect it to run well but an exception is always thrown on line 80, which is as follows:
Exception thrown at 0x00007FF6A160487C in Assignment1.exe: 0xC0000005: Access violation writing location 0x0000000000000000.
The problem is this line right here:
Value * array = new Value[size];
This declares a new array variable. You are allocating that array instead, and not your member variable array.
The answer is simple, just change it to this instead:
array = new Value[size];
I'm quite new to c++ and netbeans and have quite a problem here and I can't put my finger on what the error might be.
Building is always succesful but I get a RUN FAILED (exit value -1.073.740.940, total time: 2s) error, when running my program. My code:
Arraylist.hpp:
#include <iostream>
namespace hfu {
class Arraylist {
private:
double* members;
int size;
public:
Arraylist(int);
~Arraylist();
Arraylist(const Arraylist&);
double get(int) const;
void set(int, double);
Arraylist& operator=(const Arraylist&);
//float operator[](int);
friend std::ostream& operator<<(std::ostream&, const Arraylist&);
};
}
Arraylist.cpp:
#include "Arraylist.hpp"
#include <exception>
namespace hfu {
Arraylist::Arraylist(int i) : size(i), members(new double[size]) {
for (int i = 0; i < size; i++) {
set(i, 0);
}
}
Arraylist::~Arraylist() {
delete members;
}
Arraylist::Arraylist(const Arraylist& other) : size(other.size), members(new double[other.size]) {
for (int i = 0; i < 5; i++) {
set(i, other.get(i));
}
}
double Arraylist::get(int i) const {
if (i < 0 || i >= size) {
throw (std::exception());
} else {
return members[i];
}
}
void Arraylist::set(int i, double value) {
if (i < 0 || i >= size) {
throw (std::exception());
} else {
members[i] = value;
}
}
Arraylist& Arraylist::operator=(const Arraylist& other) {
size = other.size;
for (int i = 0; i < size; i++) {
set(i, other.get(i));
}
return *this;
}
// float Arraylist::operator [](int index) {
// return members[index];
// }
std::ostream& operator<<(std::ostream& os, const Arraylist& list) {
for (int i = 0; i < list.size; i++) {
os << "[" << list.get(i) << "]";
}
return os;
}
}
main.cpp:
#include "Arraylist.hpp"
int main() {
try {
auto a1 = hfu::Arraylist(10);
std::cout << a1 << std::endl;
auto a2 = hfu::Arraylist(10);
std::cout << a2 << std::endl;
auto a3 = hfu::Arraylist(10);
std::cout << a3 << std::endl;
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
}
I can create 2 objects of Arraylist.... but not more, it will print the first two and then fail.... but when I create shorter lists, say 3 with only size one... it will work... so I think it might be something with the memory... but I'm at a loss. Ideas?
Thanks a lot!
btw: I'm using netbeans 8.2 and mingw g++ 6.1.0
The initialization order of the member variables is defined by the order of their definitions in the class, not by their order in the initializer list. As a matter of fact, your compiler should be giving you "hfu::Arraylist::size will be initialized after" warnings.
So in your case, members gets initialized before size, thus new double[size] is called when size is still garbage. In my case it simply causes std::bad_array_new_length to be thrown. In your case, things go worse and your application crashes.
So the solution is to change
class Arraylist {
private:
double* members;
int size;
to
class Arraylist {
private:
int size;
double* members;
I have a technical problem and it's really confusing me. I apologise in advance because I may not be giving the relevant details; I don't yet why it's going wrong and it would be excessive to include all the code I'm working with.
I'm working with a large program that uses the C++ STL. I'm moving this code to a very sensitive environment without a standard clib nor STL implementaton; it will redefine malloc/free/new/delete etc... For that, I need to replace the std:: parts with my own simplified implementations. I've started with std::vector. Right now it's running in the standard ecosystem so it's the GNU libc and STL. The only thing that's changed is this vector class.
When I execute the program with the replaced class, it segfaults. I've put this through GDB and found that the program will request an object from the vector using the subscript operator. When the object reference is returned, a method is invoked and the program segfaults. It seems it can't find this method and ends up in main_arena() in GDB. The type of the object is an inherited class.
I'm really not sure at all what the problem is here. I would love to provide additional details, but I'm not sure what more I can give. I can only assume something is wrong with my vector implementation because nothing else in the program has been changed. Maybe there's something obvious that I'm doing wrong here that I'm not seeing at all.
I'm using: g++ (GCC) 4.4.5 20110214 (Red Hat 4.4.5-6)
I'd really appreciate any feedback/advice!
#ifndef _MYSTL_VECTOR_H_
#define _MYSTL_VECTOR_H_
#include <stdlib.h>
#include <assert.h>
typedef unsigned int uint;
namespace mystl
{
/******************
VECTOR
********************/
template <typename T>
class vector
{
private:
uint _size;
uint _reserved;
T *storage;
void init_vector(uint reserve)
{
if (reserve == 0)
{
_reserved = 0;
return;
}
storage = (T*)malloc(sizeof(T)*reserve);
assert(storage);
_reserved = reserve;
}
public:
vector()
{
// std::cerr << "default constructor " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
}
vector(const vector<T> &other)
{
// std::cerr << "copy constructor " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
init_vector(other.size());
_size = other.size();
for (uint i=0; i<other.size(); i++)
{
storage[i] = T(other[i]);
}
}
vector(uint init_num, const T& init_value)
{
// std::cerr << "special constructor1 " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
init_vector(init_num);
for (size_t i=0; i<init_num; i++)
{
push_back(init_value);
}
}
vector(uint init_num)
{
// std::cerr << "special constructor2 " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
init_vector(init_num);
}
void reserve(uint new_size)
{
if (new_size > _reserved)
{
storage = (T*)realloc(storage, sizeof(T)*new_size);
assert(storage);
_reserved = new_size;
}
}
void push_back(const T &item)
{
if (_size >= _reserved)
{
if (_reserved == 0) _reserved=1;
reserve(_reserved*2);
}
storage[_size] = T(item);
_size++;
}
uint size() const
{
return _size;
}
~vector()
{
if (_reserved)
{
free(storage);
storage = NULL;
_reserved = 0;
_size = 0;
}
}
// this is for read only
const T& operator[] (unsigned i) const
{
// do bounds check...
if (i >= _size || i < 0)
{
assert(false);
}
return storage[i];
}
T& operator[] (unsigned i)
{
// do bounds check...
if (i >= _size || i < 0)
{
assert(false);
}
return storage[i];
}
// overload = operator
const vector<T>& operator= (const vector<T>& x)
{
// check for self
if (this != &x)
{
_reserved = 0;
_size = 0;
storage = NULL;
init_vector( x.size() );
for(uint i=0; i<x.size(); i++)
{
storage[i] = T(x[i]);
}
_size = x.size();
}
return *this;
}
uint begin() const
{
return 0;
}
void insert(uint pos, const T& value)
{
push_back(value);
if (size() == 1)
{
return;
}
for (size_t i=size()-2; i>=pos&& i>=0 ; i--)
{
storage[i+1] = storage[i];
}
storage[pos] = value;
}
void erase(uint erase_index)
{
if (erase_index >= _size)
{
return;
}
//scoot everyone down by one
for (uint i=erase_index; i<_size; i++)
{
storage[i] = storage[i+1];
}
_size--;
}
void erase(uint start, uint end)
{
if (start > end)
{
assert(false);
}
if (end > _size)
end = _size;
for (uint i=start; i<end; i++)
{
erase(start);
}
assert(false);
}
void clear()
{
erase(0,_size);
}
bool empty() const
{
return _size == 0;
}
}; //class vector
}
#endif // _MYSTL_VECTOR_H_
Wow!
Your assignment operator also leaks memory.
Becuause you are using malloc/release the constructor to your type T will will not be called and thus you can not use your vector for anything except the most trivial of objects.
Edit:
I am bit bored this morning: Try this
#include <stdlib.h> // For NULL
#include <new> // Because you need placement new
// Because you are avoiding std::
// An implementation of swap
template<typename T>
void swap(T& lhs,T& rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
template <typename T>
class vector
{
private:
unsigned int dataSize;
unsigned int reserved;
T* data;
public:
~vector()
{
for(unsigned int loop = 0; loop < dataSize; ++loop)
{
// Because we use placement new we must explicitly destroy all members.
data[loop].~T();
}
free(data);
}
vector()
: dataSize(0)
, reserved(10)
, data(NULL)
{
reserve(reserved);
}
vector(const vector<T> &other)
: dataSize(0)
, reserved(other.dataSize)
, data(NULL)
{
reserve(reserved);
dataSize = reserved;
for(unsigned int loop;loop < dataSize;++loop)
{
// Because we are using malloc/free
// We need to use placement new to add items to the data
// This way they are constructed in place
new (&data[loop]) T(other.data[loop]);
}
}
vector(unsigned int init_num)
: dataSize(0)
, reserved(init_num)
, data(NULL)
{
reserve(reserved);
dataSize = reserved;
for(unsigned int loop;loop < dataSize;++loop)
{
// See above
new (&data[loop]) T();
}
}
const vector<T>& operator= (vector<T> x)
{
// use copy and swap idiom.
// Note the pass by value to initiate the copy
swap(dataSize, x.dataSize);
swap(reserved, x.rserved);
swap(data, x.data);
return *this;
}
void reserve(unsigned int new_size)
{
if (new_size < reserved)
{ return;
}
T* newData = (T*)malloc(sizeof(T) * new_size);
if (!newData)
{ throw int(2);
}
for(unsigned int loop = 0; loop < dataSize; ++loop)
{
// Use placement new to copy the data
new (&newData[loop]) T(data[loop]);
}
swap(data, newData);
reserved = new_size;
for(unsigned int loop = 0; loop < dataSize; ++loop)
{
// Call the destructor on old data before freeing the container.
// Remember we just did a swap.
newData[loop].~T();
}
free(newData);
}
void push_back(const T &item)
{
if (dataSize == reserved)
{
reserve(reserved * 2);
}
// Place the item in the container
new (&data[dataSize++]) T(item);
}
unsigned int size() const {return dataSize;}
bool empty() const {return dataSize == 0;}
// Operator[] should NOT check the value of i
// Add a method called at() that does check i
const T& operator[] (unsigned i) const {return data[i];}
T& operator[] (unsigned i) {return data[i];}
void insert(unsigned int pos, const T& value)
{
if (pos >= dataSize) { throw int(1);}
if (dataSize == reserved)
{
reserve(reserved * 2);
}
// Move the last item (which needs to be constructed correctly)
if (dataSize != 0)
{
new (&data[dataSize]) T(data[dataSize-1]);
}
for(unsigned int loop = dataSize - 1; loop > pos; --loop)
{
data[loop] = data[loop-1];
}
++dataSize;
// All items have been moved up.
// Put value in its place
data[pos] = value;
}
void clear() { erase(0, dataSize);}
void erase(unsigned int erase_index) { erase(erase_index,erase_index+1);}
void erase(unsigned int start, unsigned int end) /* end NOT inclusive so => [start, end) */
{
if (end > dataSize)
{ end = dataSize;
}
if (start > end)
{ start = end;
}
unsigned int dst = start;
unsigned int src = end;
for(;(src < dataSize) && (dst < end);++dst, ++src)
{
// Move Elements down;
data[dst] = data[src];
}
unsigned int count = start - end;
for(;count != 0; --count)
{
// Remove old Elements
--dataSize;
// Remember we need to manually call the destructor
data[dataSize].~T();
}
}
unsigned int begin() const {return 0;}
}; //class vector
With your current memory handling, this vector would only work with plain old data types.
To handle all types, it must ensure that objects
are actually created (malloc doesn't do that),
destroyed (free doesn't do that),
and you can't reallocate memory with realloc, because complex objects are not guaranteed to remain valid if they are byte-wise copied to another location.
Looks like the answer can be found in your question: "When the object reference is returned, a method is invoked and the program segfaults. It seems it can't find this method and ends up in main_arena() in GDB. The type of the object is an inherited class."
You probably store base class instance T in the vector, but make push_back for the instance of the class inherited from T. In push_back {storage[_size] = T(item);} you cast (actually make copy constructor T:T(const T&)) item to T (this probably named 'type cut'), then get reference to T and invoke a method of the class inherited from T using virtual table of T where the method is not defined yet/abstract. Am I right?
To make it properly work you should put T* in the vector or shared_ptr/unique_ptr depending on the ownership terms you apply to vector elements.
Generally in vector you can store only POD (Plain Old Data) types.