malloc and free memory leakage - c++

im trying to create a class which has malloc.
the class has internal struct.
the user will have pointer to the struct but he may not know about the struct or even care about it.
he must save the pointer and some functions will require the address of that struct.
so in the header of the library i did the following:
#define EELS_MAX_SLOTS 5
class EELS
{
typedef struct{
//struct difinition ...
}ee_slot_t;
public:
EELS();
uint8_t CreateSlot(uint16_t begin_addr, uint16_t length, uint8_t data_length);
~EELS();
protected:
private:
void* _slot_arr[EELS_MAX_SLOTS];
uint8_t _slot_counter;
};
and the code in the execution file:
// default constructor
EELS::EELS()
{
_slot_counter =0;
} //EELS
uint8_t EELS::CreateSlot(uint16_t begin_addr, uint16_t length, uint8_t data_length){
if (_slot_counter > EELS_MAX_SLOTS)
return NULL;
ee_slot_t* slot_p;
slot_p = malloc(sizeof(ee_slot_t))
if (!slot_p)
return NULL;
slot_p->begining = begin_addr;
slot_p->length = length;
slot_p->counter = 0; // TODO...init...
slot_p->position = 0; // TODO...init...
_slot_arr[_slot_counter] = (void*)slot_p;
_slot_counter++;
return _slot_counter;
}
// default destructor
EELS::~EELS()
{
for (int i=0; i<_slot_counter; i++)
{
free((ee_slot_t*)_slot_arr[i]);
}
}
as you can see im returning index of pointers array.. so (1-6) in this case and I'm saving the real address inside that pointers array.
but from what you see. is this safe? the free method and malloc.. there is some mistake or memory leakage?
why not vector?
because its for embedded system and the current IDE/toolchain im using doesnt support std:vectors.

What happens when _slot_counter == EELS_MAX_SLOTS.
So I think you should change the if statement
if (_slot_counter > EELS_MAX_SLOTS)
return NULL;
to
if (_slot_counter >= EELS_MAX_SLOTS)
return 0; // return type is uint8_t, not a pointer

Related

read access violation. this was 0xCDCDCDCD

I'm confused as to what I'm doing wrong? While debugging, this shows 0xcdcdcdcd {theDouble=??? }so i know my variable isnt getting stored in my mutator. How would i go about fixing this issue? Am I supposed initialize this somewhere? I am using visual studio by the way.
Thank you for the help.
int main()
{
int i = 0;
const int MAX = 4;
CLASS **object = new CLASS*[MAX];
string name = "todd";
string aString = "words";
double aDouble = 10.0;
object[i]->setDouble(aDouble);
return 0;
}
//.cpp
CLASS::Class()
{
theDouble = new double;
*theDouble = NULL;
}
CLASS::Class(double aDouble)
{
*theDouble = aDouble;
}
void CLASS::setDouble(double p)
{
*theDouble = p;
double Class::getDouble()
{return (*theDouble);}
//.h
class CLASS
{
protected:
double *theDouble;
public:
Insurance();
Insurance(double premium);
//~Insurance();
void setDouble(double p);
double getDouble();
string toString();
};`
You use CLASS, Class and Insurance in mix where you should use one name so your posted code can not compile. I replace those with IronMan.
What you see as 0xCDCDCDCD is not this pointer value but value of the pointer member theDouble. The issue comes from in constructor:
IronMan::IronMan(double aDouble)
{
*theDouble = aDouble;
}
That constructor dereferences uninitialised member variable theDouble and
since debuggers tend to fill uninitialized memory with some bytes like 0xCD you will have that as value of the pointer. Therefore you get a crash for accessing memory at such address.
One way out of it is to allocate memory for theDouble
IronMan::IronMan(double aDouble)
{
theDouble = new double(aDouble);
}
Better would be likely to avoid using pointers there at all but just have direct double data member:
protected:
double theDouble;

c++ passing arrays in constructor without defining them elsewhere

I currently have this code:
#include "stdafx.h"
#include "AddressInfo.h"
AddressInfo::AddressInfo(int ammoCount, int pointerLevel, DWORD baseAddress, DWORD* offsetArray) {
ammo = ammoCount;
numPointers = pointerLevel;
this->baseAddress = baseAddress;
offsets = (DWORD*)malloc(sizeof(offsetArray));
this->offsets = offsetArray;
};
AddressInfo::~AddressInfo() {
delete[] offsets;
}
void AddressInfo::print() {
std::cout << this->offsets[0]<< std::endl;
}
DWORD x[] = { 0x374, 0x14, 0x0 };
AddressInfo* ammo = new AddressInfo(1000, 3, (DWORD)(0x00509B74), x);
int main()
{
ammo->print();
system("pause");
}
This code works, but I want to do the following:
Instead of pre-defining the array and passing it into the constructor, I want to pass the array in as follows: {0x374,0x14,0x0}
Is this possible / is this practical
I tried typecasting: (DWORD*) {0x374,0x14,0x0}
You should use std::vector for this task and for future tasks. Look how easy and clean it makes everything
#include <iostream>
#include <vector>
class AddressInfo
{
int ammoCount;
int pointerLevel;
std::vector<uint32_t> offsets;
public:
AddressInfo(int ammoCount, int pointerLevel, std::vector<uint32_t> offsets) :
ammoCount{ ammoCount }, pointerLevel{ pointerLevel }, offsets{ offsets }
{
}
void print(size_t i)
{
std::cout << this->offsets.at(i) << std::endl;
}
};
int main()
{
AddressInfo ammo (1000, 0x00509B74, { 0x374, 0x14, 0x0 });
ammo.print(0);
ammo.print(1);
ammo.print(2);
return 0;
}
https://ideone.com/WaLiP8
This constructor is just wrong
AddressInfo::AddressInfo(
int ammoCount,
int pointerLevel,
DWORD baseAddress,
DWORD* offsetArray)
{
ammo = ammoCount;
numPointers = pointerLevel;
this->baseAddress = baseAddress;
offsets = (DWORD*)malloc(sizeof(offsetArray));
this->offsets = offsetArray;
};
first you allocate using malloc, in C++ we usually use new since malloc does not call any constructors. second sizeof doesn't give the size of the array, it gives you the size of the pointer - it is the same as writing sizeof(DWORD*)
then after you allocated something for offsets to point to, you then let it point to the parameter so what bytes you allocated with malloc are leaked.
In your destructor you assume that offsetArray has previously been allocated with new[] and passed to the constructor but how will a user of your class know that?
Imagine somebody creating your AddressInfo using an array allocated on the stack.
DWORD myArray[10];
AddressInfo adr = new AddressInfo(ammoCount,pointerLevel,baseAddress,offsetArray);
People do not want to look into the implementation to look for assumptions, that is the whole idea of putting stuff in a class, to hide the implementation.
Instead use std::array or std::vector when you work with arrays in C++, you then create a much more transparent and clean design - see Kilzone Kids answer.

Dynamic Polymorphic Memory Container - Return Value Incorrect

I am currently working on an dynamic memory container.
Basic idea of the class is that you should be able to get the iterator of an object if you really do not know it, without the use of a for loop throughout all the elements to boost performance. The issue I have is the following; when you pass your pointer address to the object you want to get the iterator of it type casts the object into the extended memory containers structures type. This type contains an extra element, an integer. (IteratorNum)
When following the code the integer within the function is set to correct value, as below would be 50. But when the returned value is set into the local integer used in the main function it is 200? I've been adding watches and cannot figure out how it is possible that the function returns 50 but value gets set to 200.
template <typename DataType> class MemoryContainer {
public:
struct LevelData : DataType
{
int element;
};
DataType &New()
{
elements++;
//Reallocate the size of the array
ld = (LevelData*)realloc(ld, sizeof(LevelData) * elements);
//Set the iteratorNumber
ld[elements - 1].element = elements - 1;
return ld[elements - 1];
}
DataType *reserve(int num)
{
return calloc(num, sizeof(DataType));
}
DataType &operator[](int i)
{
return ld[i];
}
bool inArray(DataType *type)
{
//Compare memory addresses and see if it's within.
return (type >= &ld[0]) && (type < &ld[elements - 1]);
}
static unsigned int getIterator(DataType *type)
{
// v this is 50, but in main says returns 200.
return ((LevelData*)type)->element;
}
MemoryContainer()
{
elements = 0;
}
~MemoryContainer()
{
free(data);
}
private:
unsigned int elements;
LevelData *ld;
};
struct Effective
{
//Set it to polymorphic classes
virtual void dummy()
{
}
char * testvar;
Effective(char * c)
{
testvar = c;
}
Effective(){}
};
MemoryContainer<Effective> myContainer;
int _tmain(int argc, _TCHAR* argv[])
{
//Create 200 elements in the array
for(int i = 0; i < 200; i++)
myContainer.New().testvar = "E";
//Add pointer for testing purposes to get the iterator.
Effective * pointer = &myContainer[50];
//Test setting it's value
pointer->testvar = "HEHEHE";
//Get iterator of our pointer in the array
unsigned int i = myContainer.getIterator(pointer);
printf(pointer->testvar);
system("PAUSE");
return 0;
}
I suspect it is the visual studio debugger getting confused between your two i variables. If you print out the value of i, it will print correctly. If you change the name of your variable to something else, the value shows as 50 in the debugger.
That said, your code is a mish-mash of c and c++ and won't work correctly with anything that requires a copy constructor. I would suggest at the very least using new [] rather than realloc.
Also, any user of this collection who tries to store a class with a member variable called element is going to get mighty confused.
The unsigned int i in the main function really has a value of 50, but the debugger is confusing it with the i declared in the for loop (I reproduced this with Visual Studio 2013). If you cout i it will be 50, and if you change the variable name it will show up as 50 in the debugger. I've never seen this problem before so I wonder if it might be due to your use of malloc/realloc/free with C++ objects.

C++ Access memory which isn't part of the object itself

It sounds weird, I guess, but I'm creating some low-level code for a hardware device. Dependend on specific conditions I need to allocate more space than the actual struct needs, store informations there and pass the address of the object itself to the caller.
When the user is deallocating such an object, I need to read these informations before I actually deallocate the object.
At the moment, I'm using simple pointer operations to get the addresses (either of the class or the extra space). However, I tought it would be more understandable if I do the pointer arithmetics in member functions of an internal (!) type. The allocator, which is dealing with the addresses, is the only one who know's about this internal type. In other words, the type which is returned to the user is a different one.
The following example show's what I mean:
struct foo
{
int& get_x() { return reinterpret_cast<int*>(this)[-2]; }
int& get_y() { return reinterpret_cast<int*>(this)[-1]; }
// actual members of foo
enum { size = sizeof(int) * 2 };
};
int main()
{
char* p = new char[sizeof(foo) + foo::size];
foo* bar = reinterpret_cast<foo*>(p + foo::size);
bar->get_x() = 1;
bar->get_y() = 2;
std::cout << bar->get_x() << ", " << bar->get_y() << std::endl;
delete p;
return 0;
}
Is it arguable to do it in that way?
It seems needlessly complex to do it this way. If I were to implement something like this, I would take a simpler approach:
#pragma pack(push, 1)
struct A
{
int x, y;
};
struct B
{
int z;
};
#pragma pack(pop)
// allocate space for A and B:
unsigned char* data = new char[sizeof(A) + sizeof(B)];
A* a = reinterpret_cast<A*>(data);
B* b = reinterpret_cast<B*>(a + 1);
a->x = 0;
a->y = 1;
b->z = 2;
// When deallocating:
unsigned char* address = reinterpret_cast<unsigned char*>(a);
delete [] address;
This implementation is subtly different, but much easier (in my opinion) to understand, and doesn't rely on intimate knowledge of what is or is not present. If all instances of the pointers are allocated as unsigned char and deleted as such, the user doesn't need to keep track of specific memory addresses aside from the first address in the block.
The very straightforward idea: wrap your extra logic in a factory which will create objects for you and delete them smart way.
You can also create the struct as a much larger object, and use a factory function to return an instance of the struct, but cast to a much smaller object that would basically act as the object's handle. For instance:
struct foo_handle {};
struct foo
{
int a;
int b;
int c;
int d;
int& get_a() { return a; }
int& get_b() { return b; }
//...more member methods
//static factory functions to create and delete objects
static foo_handle* create_obj() { return new foo(); }
static void delete_obj(foo_handle* obj) { delete reinterpret_cast<foo*>(obj); }
};
void another_function(foo_handle* masked_obj)
{
foo* ptr = reinterpret_cast<foo*>(masked_obj);
//... do something with ptr
}
int main()
{
foo_handle* handle = foo::create_obj();
another_function(handle);
foo::delete_obj(handle);
return 0;
}
Now you can hide any extra space you may need in your foo struct, and to the user of your factory functions, the actual value of the pointer doesn't matter since they are mainly working with an opaque handle to the object.
It seems your question is a candidate for the popular struct hack.
Is the "struct hack" technically undefined behavior?

Handling Huge Multidimensional Arrays in C++

I'm designing a game in C++ similar to Minecraft that holds an enormous amount of terrain data in memory. In general, I want to store an array in memory that is [5][4][5][50][50][50]. This isn't bad since it amounts to about 100mb of virtual memory since my structure will only be about 8 bytes.
However, I'm having trouble figuring out the best way to handle this. I do want this to be in virtual memory, but obviously not on the stack. And I keep making the mistake some how of creating this array on the stack an causing a stack overflow. What I would like to do is below. This is just code that I threw together to give you an example of what I'm doing, I have code with correct syntax on my machine, I just didn't want to clutter the post.
typedef struct modelBlock
{
// Information about the blocks
} BLOCK;
typedef struct modelGrid
{
bool empty;
BLOCK blocksArray[50][50][50];
} GRID;
class Parent
{
Child* child;
Parent(void);
}
Parent::Parent()
{
Child c;
child = &c;
}
class Child
{
GRID grids[5][4][5];
}
However, every time I do this, I cause a stack overflow (appropriate web site choice right?). I played with using pointer based arrays, but I had a lot of trouble with data being lost outside of its scope.
If anyone could give me some insight on how to get my data to store on the heap instead of the stack, or if I should use some other way of creating my array, I'd really appreciate the help. I'd like to avoid using vectors because of overhead, though I'm not sure how substantial it is.
Use boost::multi_array
If you want to allocate something on the heap, use new.
#include <memory>
class Parent
{
std::auto_ptr<Child> child; // use auto_ptr for dynamically-allocated members
Parent(const Parent&); // You probably don't want to copy this giant thing
public:
Parent();
};
Parent::Parent()
: child(new Child) // initialize members with an initializer list
{
}
Also, avoid mixing C and C++ styles. There's no reason to do
typedef struct blah{ ... } BLAH;
in C++. A struct is just a class with all of the members public by default; just like a class, you can refer to the struct type's name without using the struct tag. There's also no need to specify void for a function that takes no parameters.
boost::multi_array (linked in PigBen's answer) is a good choice over raw arrays.
If you want the class created on the heap, create it with new:
Child * c = new Child;
and then of course delete it, or better still use a smart pointer.
In order to do exactly what you're trying to do you have to declare everything as pointers (and pointers to pointers to pointers to pointers) and then allocate each one individually.
Teh sux!
A better option is to simply allocate the ginormous block in one chunk and use multiple variable along with pointer arithmetic to arrive at the correct location.
Edit: Wasn't paying attention and didn't notice your constructor. That's not only not the way to get your Child allocated on the free-store, it's a great way to create situations eliciting undefined behavior. Your Child will be gone when the constructor is through and the pointer to it will then be invalid. I wonder if you shouldn't run through some basic tutorials before trying to write a game.
Here's something that works and can be built upon without the boost dependency. One downside is it removes use of [][][] style of referencing elements, but it's a small cost and can be added.
template<class T>
class Matrix {
unsigned char* _data;
const size_t _depth;
const size_t _cols;
const size_t _rows;
public:
Matrix(const size_t& depth, const size_t& rows, const size_t& cols):
_depth(depth),
_rows(rows),
_cols(cols) {
_data = new unsigned char [depth * rows * cols * sizeof(T)];
}
~Matrix() {
delete[] _data;
}
T& at(const size_t& depthIndex, const size_t& rowIndex, const size_t& colIndex) const {
return *reinterpret_cast<T*>(_data + ((((depthIndex * _cols + colIndex) * _rows) + rowIndex) * sizeof(T)));
}
const size_t& getDepth() const {
return _depth;
}
const size_t& getRows() const {
return _rows;
}
const size_t& getCols() const {
return _cols;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Matrix<int> block(50, 50, 50);
size_t d, r, c;
for (d = 0; d < block.getDepth(); d++) {
for (r = 0; r < block.getRows(); r++) {
for (c = 0; c < block.getCols(); c++) {
block.at(d, r, c) = d * 10000000 + r * 10000 + c;
}
}
}
for (d = 0; d < block.getDepth(); d++) {
for (r = 0; r < block.getRows(); r++) {
for (c = 0; c < block.getCols(); c++) {
assert(block.at(d, r, c) == d * 10000000 + r * 10000 + c);
}
}
}
return 0;
}
A smaller example (with changed names for all the structs, to make the general principle clearer). The 'Bloe' struct is the one you want to allocate on the heap, and this is accomplished using 'new'.
struct Bla {
int arr[4][4];
};
struct Bloe {
Bla bla[2][2];
};
int main()
{
Bloe* bloe = new Bloe();
bloe->bla[1][1].arr[1][1] = 1;
return 0;
}
I did this by putting all the data in a binary file. I calculated the offset of the data and used seek() and read() to get the data when needed. The open() call is very slow so you should leave the file open during the lifetime of the program.
Below is how I understood what you showed you were trying to do in your example. I tried to keep it straightforward. Each Array of [50][50][50] is allocated in one memory chunk on the heap, and only allocated when used. There is also an exemple of access code. No fancy boost or anything special, just basic C++.
#include <iostream>
class Block
{
public:
// Information about the blocks
int data;
};
class Grid
{
public:
bool empty;
Block (*blocks)[50][50];
Grid() : empty(true) {
}
void makeRoom(){
this->blocks = new Block[50][50][50];
this->empty = false;
}
~Grid(){
if (!this->empty){
delete [] this->blocks;
}
}
};
class Parent
{
public:
Grid (* child)[4][5];
Parent()
{
this->child = new Grid[5][4][5];
}
~Parent()
{
delete [] this->child;
}
};
main(){
Parent p;
p.child[0][0][0].makeRoom();
if (!p.child[0][0][0].empty){
Block (* grid)[50][50] = p.child[0][0][0].blocks;
grid[49][49][49].data = 17;
}
std::cout << "item = "
<< p.child[0][0][0].blocks[49][49][49].data
<< std::endl;
}
This could still be more simple and straightfoward and just use one bug array of [50][50][50][5][4][5] blocks in one memory chunk on the heap, but I'll let you figure out how if this is what you want.
Also, usind dynamic allocation in class Parent only has the sole purpose to use heap instaed of stack, but for such a small array (5*4*5 pointers), allocating it on stack should not be a problem, hence it could be written.
class Parent
{
public:
Grid child[5][4][5];
};
without changing anything in the way it is used.