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.
Related
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
I have a code which is similar to the following:
myLibFunc(std::vector<char > &data)
{
// dosomthing with data
}
myFunc(char *buffer,int bufferSize)
{
std::vector<char > mydata(buffer,buffer+bufferSize);
myLibFunc(mydata);
}
The code works, but the vector allocates memory for itself and not using a memory that is already available.
How can I change the code in such a way that the vector uses the memory that already available and not allocating an extra memory?
Note that I can not change the signature of functions.
Update
I have two functions:
In one of them, I receive a buffer and I need to manipulate the memory and pass it to the next function as a vector. The function that I am trying to implement is part of an interface so I can not change it. Another function is a library that I need to call, so I can not change the signature of functions.
The problem is that the above code allocates new memory and copies the data from the buffer to it which is not optimal.
std::vector is designed to exclusively own the data it holds so doing the memory copy is the only safe way for std::vector to work. That leaves only unsafe hacks. If we can assume the function does not change the vector size, you can abuse std::vector. In my compiler (tested on g++4.8 and cpp.sh) std::vector is implemented as three pointers (to begin data, end used data and end alloc) therefore I can abuse the vector as:
#include <vector>
#include <iostream>
void myLibFunc( std::vector< char > & a )
{
for( char c : a )
{
std::cout << '[' << c << ']';
}
a[0] = 'B'
std::cout << '\n';
}
void myFunc(char *buffer,int bufferSize)
{
std::vector<char > mydata;
// cast to alterable pointers, cast should also keep
// mydata in scope until after the last assignment.
char ** abuser = (char**)&mydata;
// save old values and substitute new values
char *tmp0 = abuser[0];
abuser[0] = buffer;
char *tmp1 = abuser[1];
abuser[1] = buffer+bufferSize;
char *tmp2 = abuser[2];
abuser[2] = buffer+bufferSize;
myLibFunc(mydata);
// return old values to avoid crash when mydata goes out of scope.
abuser[0] = tmp0;
abuser[1] = tmp1;
abuser[2] = tmp2;
}
int main()
{
char p[] = "Hello World";
myFunc( &p[0] + 2, 5 );
std::cout << p << '\n';
return 0;
}
Note this abuse is likely to be non-portable and lead to unexplained crashes.
If you can not change the signature of your function it is not possible without the copy.
But a better way is to think about your interface. If you build myLibFunc on random access iterators, your problem is solved:
template <class CharRandomAccessIterator>
myLibFunc(CharRandomAccessIterator& begin, CharRandomAccessIterator& end )
{
// dosomthing with data
size = end - begin;
begin[xyz]; // access elements
}
myFunc(char *buffer,int bufferSize)
{
std::vector<char > mydata(buffer,buffer+bufferSize);
myLibFunc(mydata.begin(), mydata.end()); // This will work
myLibFunc(buffer, buffer+size); // This will work too
}
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?
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.
I want to access variable v1 & v2 in Func() while being in main()
int main(void)
{
Func();
int k = ? //How to access variable 'v1' which is in Func()
int j = ? //How to access variable 'v2' which is in Func()
}
void Func()
{
int v1 = 10;
int v2 = 20;
}
I have heard that we can access from Stack. But how to do.
Thank you.
You can't legally do that. Automatic variables disappear once execution leaves the scope they're declared in.
I'm sure there are tricks, like inspecting the stack and going "backwards" in time, but all such tricks are platform-dependent, and might break if you, for instance, cause the stack to be overwritten in main().
Why do you want to do that? Do you want those values as return values? I would introduce a struct for that, according to the meaning of the values the struct would get a suitable name
struct DivideResult {
int div;
int rem;
};
DivideResult Func() {
DivideResult r = { 10, 20 };
return r;
}
int main() {
DivideResult r = Func();
}
Otherwise, such variables are for managing local state in the function while it is activated. They don't have any meaning or life anymore after the function terminated.
Some ways you can do this are:
Declare the variables in main() and pass them by pointer or reference into Func()
Return the variable, or vector< int >, or a struct that you made, etc. of the variables to main()
Dynamically allocate the variables in Func(), and return a pointer to them. You would then have to remember to delete the allocated memory later as well.
But there is no access to the stack of Func() from main() that is standard.
You can't do that portably. When Func()'s stack frame disappears, there's no reliable way to access it. It's free to be trampled. However, in x86-64, there is something known as the red zone, which is a 128B area below the stack pointer that is safe from trampling, and theoretically you might still be able to access it, but this is not portable, easy, nor correct. Simply put, don't do it.
Here's how I would do it:
int main(void)
{
int k, j;
Func(&k, &j);
}
void Func(int *a, int *b)
{
*a = 10;
*b = 20;
}
You're in C/C++ land. There are little you cannot do.
If this your own code, you shouldn't even try to do that. Like others suggested: pass a output parameter by reference (or by pointer in C) or return the values in a struct.
However, since you asked the question, I assume you are attempting to look into something you only have binary access to. If it is just an one time thing, using a debugger will be easier.
Anyway, to answer your original question, try the following code. You have to compile it in for x86 CPU, with optimization and any stack debug flag turned off.
void f() {
int i = 12345;
int j = 54321;
}
int main()
{
int* pa = 0;
int buf[16] = {0};
f();
// get the stack pointer
__asm {
mov dword ptr [pa],ESP
}
// copy the stack, try not to do anything that "use" the stack
// before here
for (int i = 0; i < 16; ++i, --pa) {
buf[i] = *pa;
}
// print out the stack, assuming what you want to see
// are aligned at sizeof(int)
for (int i = 0; i < 16; ++i) {
std::cout << i << ":" << buf[i] << std::endl;
}
return 0;
}