I have a problem declaring a public/extern struct object between different .cpp files. I am trying to use the imgui logger to log some messages from a hook.
The program is going to crash on ExampleAppLog my_log2; -> ImGuiTextBuffer Buf; -> class ImVector -> if (Data)
Because i do this ExampleAppLog* my_log2 = new ExampleAppLog(); inside a .cpp that have a include .h with the struct ExampleAppLog in it, and a declaration of my_log2 .
Relevant code to crash ->
.h
struct ExampleAppLog
{
ImGuiTextBuffer Buf;
}
extern ExampleAppLog* my_log2;
.cpp
#include ".h"
ExampleAppLog* my_log2 = new ExampleAppLog(); //this line make it crash
imgui.h
struct ImGuiTextBuffer
{
ImVector<char> Buf;
}
class ImVector
{
public:
int Size;
int Capacity;
T* Data;
typedef T value_type;
typedef value_type* iterator;
typedef const value_type* const_iterator;
ImVector() { Size = Capacity = 0; Data = NULL; }
~ImVector() { if (Data) ImGui::MemFree(Data); }
inline bool empty() const { return Size == 0; }
inline int size() const { return Size; }
inline int capacity() const { return Capacity; }
inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }
inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }
inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } }
inline iterator begin() { return Data; }
inline const_iterator begin() const { return Data; }
inline iterator end() { return Data + Size; }
inline const_iterator end() const { return Data + Size; }
inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; }
inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; }
inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; }
inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; }
inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
inline int _grow_capacity(int size) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > size ? new_capacity : size; }
inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
inline void resize(int new_size, const T& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) Data[n] = v; Size = new_size; }
inline void reserve(int new_capacity)
{
if (new_capacity <= Capacity) return;
T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T));
if (Data) //here is the crash. Data is 0x000000000 when crashing
memcpy(new_data, Data, (size_t)Size * sizeof(T));
ImGui::MemFree(Data);
};
Exsample code ->
.h
struct ExampleAppLog
{
ImGuiTextBuffer Buf;
ImGuiTextFilter Filter;
ImVector<int> LineOffsets; // Index to lines offset
bool ScrollToBottom;
void Clear() { Buf.clear(); LineOffsets.clear(); }
void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
int old_size = Buf.size();
va_list args;
va_start(args, fmt);
Buf.appendv(fmt, args);
va_end(args);
for (int new_size = Buf.size(); old_size < new_size; old_size++)
if (Buf[old_size] == '\n')
LineOffsets.push_back(old_size);
ScrollToBottom = true;
}
void Draw(const char* title, bool* p_open = NULL)
{
ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);
ImGui::Begin(title, p_open);
if (ImGui::Button("Clear")) Clear();
ImGui::SameLine();
bool copy = ImGui::Button("Copy");
ImGui::SameLine();
Filter.Draw("Filter", -100.0f);
ImGui::Separator();
ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (copy) ImGui::LogToClipboard();
if (Filter.IsActive())
{
const char* buf_begin = Buf.begin();
const char* line = buf_begin;
for (int line_no = 0; line != NULL; line_no++)
{
const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL;
if (Filter.PassFilter(line, line_end))
ImGui::TextUnformatted(line, line_end);
line = line_end && line_end[1] ? line_end + 1 : NULL;
}
}
else
{
ImGui::TextUnformatted(Buf.begin());
}
if (ScrollToBottom)
ImGui::SetScrollHere(1.0f);
ScrollToBottom = false;
ImGui::EndChild();
ImGui::End();
}
};
extern ExampleAppLog* my_log2;
One.cpp
#include ".h"
ExampleAppLog* my_log2 = new ExampleAppLog(); //this line make it crash
void LogHook(const char* Info)
{
my_log2->AddLog(Info);
}
Two.cpp
#include ".h"
bool bDraw = true;
void Draw()
{
my_log2->Draw("Logger", &bDraw);
}
I have tried many different methodes but no luck without it ending up crashing when trying to share a extern object in multiple .cpp.
Logger documentation.
static ExampleAppLog my_log; //have tryd this but with extern etc. It still crash at the same place whan trying to share it globaly. If i do it all in one .cpp out sharing it publicly the code work
[...]
my_log.AddLog("Hello %d world\n", 123);
[...]
my_log.Draw("title");
It is hard to tell you what your problem is because important information is missing.
Are you sure that it crash while checking if Data is a null pointer?
Have you checked if this is valid at the point of crash?
Have you put a breakpoint on the constructor to see when it was called.
While it looks like you don't make any copy of those objects, it would be a good idea to prevent it if not properly supported by deleting copy and move constructor and assignment operators. See https://en.cppreference.com/w/cpp/language/function#Deleted_functions for more information.
One obvious way to see if the problem is that you call a function of ExampleAppLog before it is created is to put a breakpoint inside the constructor. From the above code, we cannot be sure if the class is created only once or multiple times (from elsewhere).
Also are you sure that you don't call Draw or LookHook before you create my_log2 object. Again, that kind of thing is trivial to test with a debugger but very hard for us to tell with only part of the code in our hand. In fact, as the above program does not have a main, it is not a MCVE.
If it really crashes when you are creating ExampleAppLog object and not when trying to use it before it was created, then most of the code above is useless and commenting out code (and remove it from the question) if it still crash, would greatly help people to help you.
On the other hand, if it crash because you are using my_log2 before it is created, then some required code to reproduce the problem is missing.
If the problem is related to initialisation order, then a singleton might be the solution. Look at the accepted answer here: How to implement multithread safe singleton in C++11 without using <mutex>.
In any case, it is hard to help you because you don't put enough effort in your question. Remember that if the code cannot easily be copied and paste, almost nobody will take the time to create a project even more when it is obvious that important lines or information are missing because with the provided information, it is almost impossible that it crash on the specified line.
In fact, in we assume that main is an empty function and that there are no other global usage of either my_log2 pointer and ExampleAppLog struct, then when would the function reserve be called.
As a bonus, if you ask good questions, you get more points on the site!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So im creating an engine from scrath(learnign purposes).
And when i test my TArray i get an Execption thrown in my Memory.h file. This happens only when im trying to test the TArray
Here is my code for TArray.h
#pragma once
#include "Memory/DynamicLinearStackAllocator.h"
template <typename T, typename Allocator = DynamicLinearStackAllocator>
class TArray
{
private:
Allocator m_Allocator;
uint32 m_ElementCount;
public:
FORCEINLINE TArray()
{
}
FORCEINLINE ~TArray()
{
m_Allocator.Destroy();
}
FORCEINLINE TArray(const uint32 InElementCount)
{
m_Allocator.Resize<T>(InElementCount, m_ElementCount);
m_ElementCount = InElementCount;
}
FORCEINLINE void Add(const T &InValue)
{
}
FORCEINLINE T* GetData() const { return m_Allocator.GetAllocator<T>(); }
FORCEINLINE uint32 Num() const
{
return m_ElementCount;
}
FORCEINLINE T& operator[](uint32 InElementIndex) const
{
check(m_ElementCount > InElementIndex);
return GetData()[InElementIndex];
}
};
namespace Tests
{
FORCEINLINE void TestArrays()
{
{
TArray<float> data(10);
check(data.Num() == 10);
for(uint32 i = 0; i < data.Num(); i++)
{
data[i] = 2.0f;
}
check(data[0] == 2.0f);
}
{
TArray<uint32> data(5);
data[0] = 10;
data[1] = 5;
check(data.Num() == 5);
check(data[0] == 10);
check(data[1] == 5);
}
{
TArray<float> data(1);
data[2] = 2.0f;
}
}
}
When i try to compile(Im using Visual Studio 2017) it gives me an execption error at this position in Memory.h
static void* Copy(void *InDestination, const void *InSource, size_t InSize)
{
check_slow(InDestination);
check_slow(InSource);
check_slow(InSize > 0);
return memcpy(InDestination, InSource, InSize);
}
The test is getting called in the main function with this code:
int main()
{
Tests::TestAssertion();
Tests::TestMemory();
Tests::TestAllocator();
Tests::TestArrays();
return 0;
}
my goal currently is to look if the logger shows me the error here:
{
TArray<float> data(1);
data[2] = 2.0f;
}
here is a screenshot of the full error https://gyazo.com/6c1d6779623ffea97504f5b23f9fd7da
edit: here is the code for the allocator
#pragma once
#include <malloc.h>
#include "Core.h"
#define MEMORY_ALIGMENT 16
struct Memory
{
// TODO:Rework types.
static void* Allocate(const int32 InCount, const size_t InSize)
{
check_slow(InCount > 0);
check_slow(InSize > 0);
const size_t size = InSize * InCount;
return _aligned_malloc(size, MEMORY_ALIGMENT);
}
static void Free(void *InBlock)
{
check_slow(InBlock);
_aligned_free(InBlock);
}
static void* Copy(void *InDestination, const void *InSource, size_t InSize)
{
check_slow(InDestination);
check_slow(InSource);
check_slow(InSize > 0);
return memcpy(InDestination, InSource, InSize);
}
};
void* operator new (size_t InSize)
{
return Memory::Allocate(1, InSize);
}
void operator delete (void* InBlock)
{
Memory::Free(InBlock);
}
namespace Tests
{
struct MemoryTestStruct
{
uint32 p0;
uint32 p1;
uint32 p2;
uint32 p3;
};
FORCEINLINE void TestMemory()
{
MemoryTestStruct *t = new MemoryTestStruct();
check(t);
delete t;
}
}
edit2: Here is the code for the StackAlloctor
#pragma once
#include "../Core.h"
class DynamicLinearStackAllocator
{
private:
void *m_Data;
public:
template <typename T>
FORCEINLINE void Resize(const uint32 InElementCount, const uint32 InPreviousElementCount)
{
void *temp = Memory::Allocate(InElementCount, sizeof(T));
if (InPreviousElementCount > 0)
{
const SIZE_T size = sizeof(T) * InPreviousElementCount;
Memory::Copy(temp, m_Data, size);
Memory::Free(m_Data);
}
m_Data = temp;
}
template <typename T>
FORCEINLINE T* GetAllocator() const
{
return (T*)m_Data;
}
FORCEINLINE void Destroy()
{
Memory::Free(m_Data);
}
};
namespace Tests
{
FORCEINLINE void TestAllocator()
{
DynamicLinearStackAllocator alloc;
alloc.Resize<float>(2, 0);
alloc.Destroy();
}
}
You're not showing the code for your Allocator, but the problem is probably this line in your TArray constructor:
m_Allocator.Resize<T>(InElementCount, m_ElementCount);
At this point, m_ElementCount has not been initialized and will have some random value in it. Resize is then probably trying to free up memory that hasn't been allocated (because of the uninitialized value in m_ElementCount). You should pass in a 0 for the second parameter of the Resize call in your constructor
m_Allocator.Resize<T>(InElementCount, 0);
since there is no existing allocated memory to free.
Also, your default constructor for TArray should initialize m_Allocator.m_data to nullptr (or add a default constructor to DynamicLinearStackAllocator to do that) and set m_ElementCount to 0.
I want to create a function that returns a contiguous 2D array in C++.
It is not a problem to create the array using the command:
int (*v)[cols] = new (int[rows][cols]);
However, I am not sure how to return this array as a general type for a function. The function is:
NOT_SURE_WHAT_TYPE create_array(int rows, int cols)
{
int (*v)[cols] = new (int[rows][cols]);
return v;
}
I tried double*[] and double** and both don't work. I wouldn't want to use double*, since I want to access this array from outside as a 2D array.
Related question: How do I declare a 2d array in C++ using new?
If you want to create an array where the data is contiguous and you don't want a 1-dimensional array (i.e. you want to use the [][] syntax), then the following should work. It creates an array of pointers, and each pointer points to a position into a pool of memory.
#include <iostream>
#include <exception>
template <typename T>
T** create2DArray(unsigned nrows, unsigned ncols, const T& val = T())
{
if (nrows == 0)
throw std::invalid_argument("number of rows is 0");
if (ncols == 0)
throw std::invalid_argument("number of columns is 0");
T** ptr = nullptr;
T* pool = nullptr;
try
{
ptr = new T*[nrows]; // allocate pointers (can throw here)
pool = new T[nrows*ncols]{val}; // allocate pool (can throw here)
// now point the row pointers to the appropriate positions in
// the memory pool
for (unsigned i = 0; i < nrows; ++i, pool += ncols )
ptr[i] = pool;
// Done.
return ptr;
}
catch (std::bad_alloc& ex)
{
delete [] ptr; // either this is nullptr or it was allocated
throw ex; // memory allocation error
}
}
template <typename T>
void delete2DArray(T** arr)
{
delete [] arr[0]; // remove the pool
delete [] arr; // remove the pointers
}
int main()
{
try
{
double **dPtr = create2DArray<double>(10,10);
dPtr[0][0] = 10; // for example
delete2DArray(dPtr); // free the memory
}
catch(std::bad_alloc& ex)
{
std::cout << "Could not allocate array";
}
}
Note that only 2 allocations are done. Not only is this more efficient due to the lesser amounts of allocations done, we now have a better chance of doing a rollback of the allocated memory if a memory allocation fails, unlike the "traditional" way of allocating a 2D array in non-contiguous memory:
// The "traditional" non-contiguous allocation of a 2D array (assume N x M)
T** ptr;
ptr = new T*[N];
for (int i = 0; i < N; ++i)
ptr[i] = new T [M]; // <<-- What happens if new[] throws at some iteration?
If new[] throws an exception somewhere during the operation of the for loop, you have to roll back all of the successful calls to new[] that happened previously -- that requires more code and adds complexity.
Note how you deallocate the memory in the contiguous version -- just two calls to delete[] when allocated contiguously instead of a loop calling delete[] for each row.
Also, since the data is in contiguous memory, algorithms, functions, etc. that assume that the data is in contiguous memory, just like a one-dimensional array, can now be used by specifying the start and end range for the M*N matrix:
[&array[0][0], &array[M-1][N])
For example:
std::sort(&myArray[0][0], &myArray[M-1][N]);
will sort the entire matrix in ascending order, starting from index [0][0] up until the last index [M-1][N-1].
You can improve on the design by making this a true class instead of having allocation / deallocation as 2 separate functions.
Edit: The class is not RAII-like, just as the comment says. I leave that as an exercise for the reader. One thing missing from the code above is the check that nRows and nCols are > 0 when creating such an array.
Edit 2: Added a try-catch to ensure a proper roll back of the memory allocation is done if a std::bad_alloc exception is thrown attempting to allocate memory.
Edit: For a 3 dimensional array example of code similar to the above see this answer. Included is code to roll back allocations if the allocation fails.
Edit: Rudimentary RAII class added:
template <typename T>
class Array2D
{
T** data_ptr;
unsigned m_rows;
unsigned m_cols;
T** create2DArray(unsigned nrows, unsigned ncols, const T& val = T())
{
T** ptr = nullptr;
T* pool = nullptr;
try
{
ptr = new T*[nrows]; // allocate pointers (can throw here)
pool = new T[nrows*ncols]{ val }; // allocate pool (can throw here)
// now point the row pointers to the appropriate positions in
// the memory pool
for (unsigned i = 0; i < nrows; ++i, pool += ncols)
ptr[i] = pool;
// Done.
return ptr;
}
catch (std::bad_alloc& ex)
{
delete[] ptr; // either this is nullptr or it was allocated
throw ex; // memory allocation error
}
}
public:
typedef T value_type;
T** data() {
return data_ptr;
}
unsigned get_rows() const {
return m_rows;
}
unsigned get_cols() const {
return m_cols;
}
Array2D() : data_ptr(nullptr), m_rows(0), m_cols(0) {}
Array2D(unsigned rows, unsigned cols, const T& val = T())
{
if (rows == 0)
throw std::invalid_argument("number of rows is 0");
if (cols == 0)
throw std::invalid_argument("number of columns is 0");
data_ptr = create2DArray(rows, cols, val);
m_rows = rows;
m_cols = cols;
}
~Array2D()
{
if (data_ptr)
{
delete[] data_ptr[0]; // remove the pool
delete[] data_ptr; // remove the pointers
}
}
Array2D(const Array2D& rhs) : m_rows(rhs.m_rows), m_cols(rhs.m_cols)
{
data_ptr = create2DArray(m_rows, m_cols);
std::copy(&rhs.data_ptr[0][0], &rhs.data_ptr[m_rows-1][m_cols], &data_ptr[0][0]);
}
Array2D(Array2D&& rhs) noexcept
{
data_ptr = rhs.data_ptr;
m_rows = rhs.m_rows;
m_cols = rhs.m_cols;
rhs.data_ptr = nullptr;
}
Array2D& operator=(Array2D&& rhs) noexcept
{
if (&rhs != this)
{
swap(rhs, *this);
rhs.data_ptr = nullptr;
}
return *this;
}
void swap(Array2D& left, Array2D& right)
{
std::swap(left.data_ptr, right.data_ptr);
std::swap(left.m_cols, right.m_cols);
std::swap(left.m_rows, right.m_rows);
}
Array2D& operator = (const Array2D& rhs)
{
if (&rhs != this)
{
Array2D temp(rhs);
swap(*this, temp);
}
return *this;
}
T* operator[](unsigned row)
{
return data_ptr[row];
}
const T* operator[](unsigned row) const
{
return data_ptr[row];
}
void create(unsigned rows, unsigned cols, const T& val = T())
{
*this = Array2D(rows, cols, val);
}
};
int main()
{
try
{
Array2D<double> dPtr(10, 10);
std::cout << dPtr[0][0] << " " << dPtr[1][1] << "\n";
}
catch (std::exception& ex)
{
std::cout << ex.what();
}
}
Unless the size of the two dimensions is known at compile time, your don't have much choice: allocate a single rows*cols array of ints, and roll your own 2D indexing with integer multiplication and addition. Wrapping this in a class can produce a nice-looking syntax for accessing array elements with square bracket operator. Since your array is 2D, you will need to use proxy (AKA "surrogate") objects for the first level of data access.
Here is a small sample code that uses std::vector<T> for maintaining a contiguous memory region in dynamic memory:
template<class T>
class Array2D {
vector<T> data;
size_t cols;
public:
// This is the surrogate object for the second-level indexing
template <class U>
class Array2DIndexer {
size_t offset;
vector<U> &data;
public:
Array2DIndexer(size_t o, vector<U> &dt) : offset(o), data(dt) {}
// Second-level indexing is done in this function
T& operator[](size_t index) {
return data[offset+index];
}
};
Array2D(size_t r, size_t c) : data (r*c), cols(c) {}
// First-level indexing is done in this function.
Array2DIndexer<T> operator[](size_t index) {
return Array2DIndexer<T>(index*cols, data);
}
};
You can now use Array2D<int> as if it were a built-in C++ array:
Array2D<int> a2d(10, 20);
for (int r = 0 ; r != 10 ; r++) {
for (int c = 0 ; c != 20 ; c++) {
a2d[r][c] = r+2*c+1;
}
}
Running demo on ideone.
Since you're using C++ and not C, I would recommend to use one vector instead of messing around with new/delete.
You can define one contiguous block of memory like this:
std::vector<int> my_matrix(rows*cols);
And now you access this vector in a 2d-array-like way with the formula i*n + j, with i being the row index, j the column index and n the length of a row:
my_matrix[i*n + j];
That's the same as accessing a 2d array with array[i][j]. But now you have the advantage of one contiguous block of memory, you don't need to bother about new/delete and you can easily share and return this vector object with functions.
handling raw memory ressources is often icky. Best shot is a simple wrapper as :
struct array2D : private std::vector<int>
{
typedef std::vector<int> base_type;
array2D() : base_type(), height_(0), width_(0) {}
array2D(std::size_t h, std::size_t w) : base_type(h*w), height_(h), width_(w);
int operator()(std::size_t i, std::size_t j) const
{
return base_type::operator[](i+j*height_);
}
int& operator()(std::size_t i, std::size_t j)
{
return base_type::operator[](i+j*height_);
}
std::size_t rows() const { return height_; }
std::size_t cols() const { return width_; }
private:
std::size_t height_, width_;
}
private inheritance let you grab all the goodies from vector, just add your 2D constructor. Ressources management is free as vector ctor/dtor will do their magic. Obviously, the i+h*j can be changed to whateever storage order you want.
vector< vector< int > > is 2D but won't be contiguous in memory.
Your function then become :
array2D create_array(int rows, int cols)
{
return array2D(cols,rows);
}
EDIT:
You can also retrieve other vector interface parts like begin/end or size with the usign clause to make the private inherited member functions public again.
None of the ways of defining a 2D dynamic array in standard C++ are entirely satisfactory in my opinion.
You end up having to roll your own solutions. Luckily there is already a solution in Boost. boost::multi_array:
#include "boost/multi_array.hpp"
template<typename T>
boost::multi_array<T, 2> create_array(int rows, int cols) {
auto dims = boost::extents[rows][cols];
return boost::multi_array<T, 2>(dims);
}
int main() {
auto array = create_array<int>(4, 3);
array[3][2] = 0;
}
Live demo.
The "Rudimentary RAll" class provided by PaulMcKenzie is an excellent solution. In my use of it I did find a memory leak which is fixed in the version shown below.
The memory leak was due to an issue with
Array2D& operator=(Array2D&& rhs) noexcept.
The statement rhs.m_dataPtr = nullPtr needed to be removed in order to allow the rhs destructor to delete the original data (pool and pointers) swapped from lhs.
Here is the corrected code for the "Rudimentary RAll" class provided by PaulMcKenzie
template <typename T>
class Array2D
{
T** data_ptr;
unsigned m_rows;
unsigned m_cols;
T** create2DArray(unsigned nrows, unsigned ncols, const T& val = T())
{
T** ptr = nullptr;
T* pool = nullptr;
try
{
ptr = new T*[nrows]; // allocate pointers (can throw here)
pool = new T[nrows*ncols]{ val }; // allocate pool (can throw here)
// now point the row pointers to the appropriate positions in
// the memory pool
for (unsigned i = 0; i < nrows; ++i, pool += ncols)
ptr[i] = pool;
// Done.
return ptr;
}
catch (std::bad_alloc& ex)
{
delete[] ptr; // either this is nullptr or it was allocated
throw ex; // memory allocation error
}
}
public:
typedef T value_type;
T** data() {
return data_ptr;
}
unsigned get_rows() const {
return m_rows;
}
unsigned get_cols() const {
return m_cols;
}
Array2D() : data_ptr(nullptr), m_rows(0), m_cols(0) {}
Array2D(unsigned rows, unsigned cols, const T& val = T())
{
if (rows == 0)
throw std::invalid_argument("number of rows is 0");
if (cols == 0)
throw std::invalid_argument("number of columns is 0");
data_ptr = create2DArray(rows, cols, val);
m_rows = rows;
m_cols = cols;
}
~Array2D()
{
if (data_ptr)
{
delete[] data_ptr[0]; // remove the pool
delete[] data_ptr; // remove the pointers
}
}
Array2D(const Array2D& rhs) : m_rows(rhs.m_rows), m_cols(rhs.m_cols)
{
data_ptr = create2DArray(m_rows, m_cols);
std::copy(&rhs.data_ptr[0][0], &rhs.data_ptr[m_rows-1][m_cols], &data_ptr[0][0]);
}
Array2D(Array2D&& rhs) noexcept
{
data_ptr = rhs.data_ptr;
m_rows = rhs.m_rows;
m_cols = rhs.m_cols;
rhs.data_ptr = nullptr;
}
Array2D& operator=(Array2D&& rhs) noexcept
{
if (&rhs != this)
{
swap(rhs, *this);
}
return *this;
}
void swap(Array2D& left, Array2D& right)
{
std::swap(left.data_ptr, right.data_ptr);
std::swap(left.m_cols, right.m_cols);
std::swap(left.m_rows, right.m_rows);
}
Array2D& operator = (const Array2D& rhs)
{
if (&rhs != this)
{
Array2D temp(rhs);
swap(*this, temp);
}
return *this;
}
T* operator[](unsigned row)
{
return data_ptr[row];
}
const T* operator[](unsigned row) const
{
return data_ptr[row];
}
void create(unsigned rows, unsigned cols, const T& val = T())
{
*this = Array2D(rows, cols, val);
}
};
int main()
{
try
{
Array2D<double> dPtr(10, 10);
std::cout << dPtr[0][0] << " " << a2[0][0] << "\n";
}
catch (std::exception& ex)
{
std::cout << ex.what();
}
}
I think you should write a simple class to wrap a 1-dim array. Then you can implement a 2-dim array with operator() overloading for getting values and deconstruct func for release the memory. Code as below:
#include <assert.h>
template <typename T>
class Array_2D
{
private:
T *data_inside;
public:
int size[2];
Array_2D(int row, int column);
~Array_2D();
//
T operator()(int index1, int index2){
return data_inside[get_index(index1, index2)];
}
int get_index(int index1, int index2){
if(index1>=0 and index1<size[0] and index2>=0 and index2<=size[1]){
return index1*size[0] + index2;
}else{
assert("wrong index for array!" == "True");
}
}
};
template <typename T>
Array_2D<T>::Array_2D(int row, int column)
{
size[0] = row;
size[1] = column;
data_inside = new T[row*column];
}
template <typename T>
Array_2D<T>::~Array_2D()
{
// 使用析构函数,自动释放资源
delete[] data_inside;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have made a small mechanism that replaces the regular new operator.
Basically we allocate a pool of memory (like 16mb) and when new is called, return
an offset to it that grows until there is no more room and we make another pool. A pool
is deleted only when all of the elements in that pool are freed.
I have tested this class and it works great and around 8-15 times faster than the original new.
There is a problem however: I incorporated it into my other project which is huge in size, it
works normally except the memory usage grows very quickly. Basically the pools aren't freed because
some items in them are not deleted at all. Also, there are many calls to new(0) from STL containers
to which I dont know how should it respond.
Here is the code:
namespace rt
{
class pool
{
friend class alloc;
private:
unsigned int _numRecords;
unsigned int _sizeLeft;
char* _ptr;
char* _data;
};
class alloc
{
public:
alloc();
alloc(int mb);
~alloc();
void* allocate(unsigned int size);
void constructPool(unsigned int idx);
void destroyPool(unsigned int idx);
void deallocate(void* ptr);
private:
const static unsigned int _numPools = 256;
const static unsigned int _poolSize = 15*1024*1024;
const static unsigned int _poolReplaceBound = 1*1024*1024; // if 1mb or less left we can replace it
pool* _pools[_numPools];
unsigned int _curPoolIdx;
};
That was the header.
Here is the implementation:
namespace rt
{
class pool
{
friend class alloc;
private:
unsigned int _numRecords;
unsigned int _sizeLeft;
char* _ptr;
char* _data;
};
class alloc
{
public:
alloc();
alloc(int mb);
~alloc();
void* allocate(unsigned int size);
void constructPool(unsigned int idx);
void destroyPool(unsigned int idx);
void deallocate(void* ptr);
private:
const static unsigned int _numPools = 256;
const static unsigned int _poolSize = 15*1024*1024;
const static unsigned int _poolReplaceBound = 1*1024*1024; // if 1mb or less left we can replace it
pool* _pools[_numPools];
unsigned int _curPoolIdx;
};
extern alloc default_allocator;
}
#define RT_SAFE_MEM
namespace rt
{
alloc default_allocator;
alloc::alloc()
{
for(int i = 0; i < _numPools; i++) _pools[i] = NULL;
_curPoolIdx = 0;
constructPool(_curPoolIdx);
}
alloc::~alloc()
{
}
void alloc::constructPool(unsigned int idx)
{
_pools[idx] = (pool*)malloc(sizeof(pool));
_pools[idx]->_numRecords = 0;
_pools[idx]->_sizeLeft = _poolSize;
_pools[idx]->_data = (char*)calloc(_poolSize, 1);
_pools[idx]->_ptr = _pools[idx]->_data;
}
void alloc::destroyPool(unsigned int idx)
{
free(_pools[idx]->_data);
free(_pools[idx]);
_pools[idx] = NULL;
}
void* alloc::allocate(unsigned int size)
{
if(size == 0)
{
return NULL;
}
#ifdef RT_SAFE_MEM
if(size > _poolSize)
{
MessageBox(NULL, "Allocation size exceeded maximum.", "Executor", MB_OK);
return NULL;
}
if(*(_pools[_curPoolIdx]->_ptr) != 0)
{
//leak
unsigned int leaksize = strlen(_pools[_curPoolIdx]->_ptr);
char str[50];
sprintf(str, "Memory corruption detected: wrote extra %u bytes. \nExporting to corrupt.txt", leaksize);
FILE* fp = fopen("corrupt.txt", "w");
fwrite(_pools[_curPoolIdx]->_ptr, 1, leaksize, fp);
fclose(fp);
MessageBox(NULL, str, "Executor", MB_OK);
return NULL;
}
#endif
if(_pools[_curPoolIdx]->_sizeLeft <= size)
{
//not enough size in this pool
//make a new one
_curPoolIdx++;
//printf("expand");
constructPool(_curPoolIdx);
return allocate(size);
}
else
{
void* ans = (void*)_pools[_curPoolIdx]->_ptr;
_pools[_curPoolIdx]->_ptr+=size;
_pools[_curPoolIdx]->_sizeLeft-=size;
_pools[_curPoolIdx]->_numRecords++;
return ans;
}
}
void alloc::deallocate(void* ptr)
{
for(int i = 0; i <= _curPoolIdx; i++)
{
if(ptr >= _pools[i]->_data && ptr < _pools[i]->_ptr)
{
//pool i contains this object
//printf("found %d\n", i);
_pools[i]->_numRecords--;
if(_pools[i]->_numRecords == 0 && _pools[i]->_sizeLeft <= _poolReplaceBound)
{
//replace this pool
printf("replacing %d\n", i);
destroyPool(i);
if(_curPoolIdx == 0) constructPool(0);
else
{
for(int j = i; j < _numPools-1; j++)
{
_pools[j] = _pools[j+1];
}
_curPoolIdx--;
}
}
return;
}
}
#ifdef RT_SAFE_MEM
char str[50];
sprintf(str, "Attempted to deallocate foreign memory at 0x%.8X.", ptr);
MessageBox(NULL, str, "Executor", MB_OK);
#endif
}
}
If anyone sees a bug or a major problem, let me know.
Thanks!
I suggest you do all the below steps:
Write a test program to test that your program runs bug-free or "has any problems"
use a debugger to find bugs, not the SO's audience :-P
Instead of posting a full listing of your code you should write-up what your code does - this will serve you as a great reference point in future and also will be a useful documentation for what (and how) your code does
I've got this here class defined in a header file:
class E_IndexList {
public:
E_UIntegerList* l;
inline void *data() { // retrieve packed data: stride depends on type (range)
return l->data();
}
inline void insert(unsigned value) {
if (value > maxval[l->range]) {
promote();
insert(value);
} else {
l->push_back(value);
}
}
inline size_t size() {
return l->size();
}
inline unsigned long get(int index) {
return l->get(index);
}
void promote() {
if (l->range == E_UIntegerList::e_byte) {
E_UShortList *new_short_list = new E_UShortList(*((E_UByteList*)l));
delete l;
l = new_short_list;
} else if (l->range == E_UIntegerList::e_short) {
E_UIntList *new_int_list = new E_UIntList(*((E_UShortList*)l));
delete l;
l = new_int_list;
} else ASSERT(false);
}
// start off with bytes by default
E_IndexList() {
l = new E_UByteList;
}
E_IndexList(E_UIntegerList::int_bits range) {
switch(range) {
case E_UIntegerList::e_byte:
l = new E_UByteList;
break;
case E_UIntegerList::e_short:
l = new E_UShortList;
break;
case E_UIntegerList::e_int:
l = new E_UIntList;
break;
default:
ASSERT(false);
break;
}
}
E_IndexList(const E_IndexList& cpy) { // copy ctor
switch(cpy.l->range) {
case E_UIntegerList::e_byte:
l = new E_UByteList(((E_UByteList*)cpy.l)->list);
break;
case E_UIntegerList::e_short:
l = new E_UShortList(((E_UShortList*)cpy.l)->list);
break;
case E_UIntegerList::e_int:
l = new E_UIntList(((E_UShortList*)cpy.l)->list);
break;
default:
ASSERT(false);
break;
}
}
~E_IndexList() {
delete l;
}
};
Here are some more classes it makes use of:
static const unsigned long maxval[] = {0xff,0xffff,0xffffffff};
class E_UIntegerList {
public:
enum int_bits {e_byte = 0, e_short = 1, e_int = 2};
virtual ~E_UIntegerList() {}
int_bits range;
virtual void push_back(int i) = 0;
virtual void *data() = 0;
virtual size_t size() = 0;
virtual unsigned long get(int index) = 0;
};
struct E_UByteList:public E_UIntegerList {
std::vector<unsigned char> list;
E_UByteList() {
range = e_byte;
}
E_UByteList(const std::vector<unsigned char>& copy) {
list = copy;
}
inline void push_back(int i) {
list.push_back(i);
}
inline void *data() { return list.data(); }
inline size_t size() { return list.size(); }
inline unsigned long get(int index) { return list[index]; }
};
struct E_UShortList:public E_UIntegerList {
std::vector<unsigned short> list;
E_UShortList() {
range = e_short;
}
E_UShortList(const std::vector<unsigned short>& copy) {
list = copy;
}
E_UShortList(const E_UByteList& promotee) {
range = e_short;
list.assign(promotee.list.begin(),promotee.list.end()); // assignment should be compatible
}
inline void push_back(int i) {
list.push_back(i);
}
inline void *data() { return list.data(); }
inline size_t size() { return list.size(); }
inline unsigned long get(int index) { return list[index]; }
};
struct E_UIntList:public E_UIntegerList {
std::vector<unsigned int> list;
E_UIntList() {
range = e_int;
}
E_UIntList(const std::vector<unsigned int>& copy) {
list = copy;
}
E_UIntList(const E_UShortList& promotee) {
range = e_int;
list.assign(promotee.list.begin(),promotee.list.end());
}
inline void push_back(int i) {
list.push_back(i);
}
inline void *data() { return list.data(); }
inline size_t size() { return list.size(); }
inline unsigned long get(int index) { return list[index]; }
};
Now the way that I use this class is I have a std::vector<E_IndexList> that I use as a container of index lists.
The strange behavior is that when I run the program sometimes it has no problems and sometimes it asserts false.
So this is a big red flag for me because something super fishy is going on. I will very likely end up abandoning the entire E_IndexList until I start working on game netcode which is a long ways off. But, I'd like to know what's going on here.
Every ctor I have sets the range to a valid value out of the enum in E_UIntegerList, so how could that assertion ever get tripped? And I can't begin to come up with an explanation of why the behavior is inconsistent. The test that calls this code is not multi-threaded.
Your E_UByteList from-vector constructor does not set the range value.
The entire design is a bit shoddy; you should learn how to use constructor initializer lists, and I would probably endow the base class with a protected constructor that sets the range value and which can be invoked from within the derived constructors' initializers.
You didn't define an assignment operator. See rule of three.
Your constructors such as this one:
E_UByteList(const std::vector<unsigned char>& copy) {
list = copy;
}
do not initialise range from the parent E_UIntegerList class.
I am trying to create custom array indexed from 1 using subscript operator. Getting value works fine, but I have no clue, why assign using subscript operator doesn't work.
class CEntry {
public:
CKey key;
CValue val;
CEntry(const CKey& key, const CValue& val) {
this->key = key;
this->val = val;
}
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
};
...
class EntriesArray {
public:
CEntry **entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry*[length];
int i;
for (i = 0; i < length + 1; i++) {
entries[i] = NULL;
}
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
};
Constructs array this way
EntriesArray a(5);
This works
a.entries[0] = new CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
This doesn't work
a[1] = new CEntry(CKey(1), CValue(1));
EDIT:
Using
CEntry *operator=( CEntry *orig)
it compiles okey, but gdb stops at
No memory available to program now: unsafe to call malloc warning: Unable to restore previously selected frame
with backtrace
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ffff8
0x00000001000013c8 in CEntry::operator= (this=0x0, orig=0x1001008d0) at /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp:20
20 /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp: No such file or directory.
in /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp
At first... This:
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
Shouldn't work (this should result in recursive call of operator=).
The second thing is that you're trying to assign CEntry * to CEntry, this would work if you had CEntry *operator=( CEntry *orig), but I think this is bad coding practice.
This question may be related to this one.
I tried to fix your code; I believe that this is what you were trying to do:
(tested this code on g++ 5.3.0)
#include <iostream>
#include <stdexcept>
#include <string>
// Some implementation for CKey and CValue:
typedef int CKey;
struct CValue {
int value;
CValue(int value=0) : value(value) {}
};
class CEntry {
public:
CKey key;
CValue val;
CEntry(): key(0), val(0) {}
CEntry(const CKey& key, const CValue& val): key(key), val(val) {}
CEntry& operator= (const CEntry& b) {
this->key = b.key;
this->val = b.val;
return *this;
};
};
class EntriesArray {
public:
CEntry *entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry[length];
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw std::domain_error("out of bounds!");
}
return entries[index - 1];
};
};
int main(int argc, char* argv[]) {
using namespace std;
EntriesArray a(5);
// This works
a.entries[0] = CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
// This doesn't work
a[1] = CEntry(CKey(2), CValue(2));
cout << a[1].val.value << endl;
}
Also you might want to use a[1] as a[1].val.value e.g.:
cout << a[1] << endl;
To do this just add to this line to cEntry:
operator int() { return val.value; }
I hope it helps.
You could try replacing
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
with
void Add(const int index, CEntry *pEntry) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
entries[index - 1] = pEntry;
};
but since you are now storing references to objects allocated on the heap (with new) you will need a destructor ~EntriesArray() to delete them all.
Because EntriesArray::operator[] returns a CEntry &, but new CEntry returns a CEntry *.
Perhaps you want a[1] = CEntry(CKey(1), CValue(1))? (no new.)
By the way, your current definition of CEntry::operator= will lead to a stack overflow.
This
return *entries[index - 1];
dereferences a NULL pointer.
You want the pointer itself to be overwritten by a[1] = new CEntry(CKey(1), CValue(1));, not the pointed-to-value.
Try this:
class EntriesArray
{
public:
int length;
CEntry **entries;
EntriesArray( int length ) : length(length), entries(new CEntry*[length]())
{
}
// defaulted special member functions are inappropriate for this class
EntriesArray( const EntriesArray& ); // need custom copy-constructor
~EntriesArray(); // need custom destructor
EntriesArray& operator=(const EntriesArray&); // need custom assignment-operator
CEntry*& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return entries[index - 1];
}
};
Further to my comment above:
To make it work with writing new values, you probably need something like this
(I haven't double checked for off by one or ptr vs reference stuff)
CEntry& operator[] (const int index) {
if (index < 1) {
throw ArrayOutOfBounds();
}
// Add default elements between the current end of the list and the
// non existent entry we just selected.
//
for(int i = length; i < index; i++)
{
// BUG is here.
// We don't actually know how "entries" was allocated, so we can't
// assume we can just add to it.
// We'd need to try to resize entries before coming into this loop.
// (anyone remember realloc()? ;-)
entries[i] = new CEntry();
}
return *entries[index - 1];
};