C++ dereferencing an instance - c++

I'm new to C++ and I'm trying to dry up my code, for example:
void gethit () {
Gert.hitbox(AA.x, AA.damage);
Gert.hitbox(AB.x, AB.damage);
Gert.hitbox(AC.x, AC.damage);
Gert.hitbox(AD.x, AD.damage);
Gert.hitbox(Terbil.x, Terbil.damage);
}
AA, AB, AC, AD and Terbil are all instances of a class called Entity with variables x and damage.
Every time I want to add a new instance I'll have to come into this function and add it manually. I'm trying to add all of the address of the instances to an array like so:
void * p_enemys[10];
p_enemys[0] = &AA;
p_enemys[1] = &AB;
p_enemys[2] = ∾
p_enemys[3] = &AD;
p_enemys[4] = &Terbil;
Just wondering how I could call a function from the instance via the array, I tried to do
for(int i = 0; i < 10; i++;) {
Gert.hitbox(p_enemys[i].x, p_enemys[i].damage);
}
and g++ compiler spits out: "request for member `damage' in `p_enemys[i]', which is of non-aggregate type `void *'"
I don't really need to use arrays specifically any help is very appreciated.
Changes made, thanks #gldraphael!
vector <Entity*> p_Enemys(10);
void gethit () {
for (int i = 0; i < 10; ++i) {
Entity * ienemy = (Entity*) p_Enemys[i];
Gert.hitbox((ienemy->x), (ienemy->damage));
}
}

You can make an a std::vector as follows:
std::vector <Entity*> p_Enemys(10);
The assigning part remains the same:
p_enemys[0] = &AA;
p_enemys[1] = &AB;
p_enemys[2] = &AC;
p_enemys[3] = &AD;
p_enemys[4] = &Terbil;
You can then loop through the p_enemys as follows:
for(auto i : p_enemys) {
Gert.hitbox(i->x, i->damage);
}
So what was it that you missed?
The array was declared as an array of void*
So, in the loop, p_enemys[i] returned a void*.
Also class/struct members are accessed using a dereferencing operator ->. You used the membership operator . instead.
So this code should have worked instead:
for(int i = 0; i < p_enemys.size(); i++;) { //
Entity * ienemy = (Entity*) p_enemys[i]; // cast the void* into a Entity*
Gert.hitbox(ienemy->x, ienemy->damage);
}
As a general rule, avoid void*s whenever possible.

Related

a value of type "void *" cannot be assigned to an entity of type "RANDOMSTRUCT *"

So I was working on malloc in void. And I have a code:
int iInitRandomPhaseArrays(WS_ELEMENT *Aufbau, RANDOMSTRUCT **random)
{
WS_ELEMENT *Act;
int iCounter = 0, i;
RANDOMSTRUCT *dummy;
Act = Aufbau;
if (*random != NULL)
return -1;
while (Act != NULL)
{
if (Act->operation == Linsenarray)
iCounter++;
Act = Act->pNext;
}
if (iCounter)
{
dummy = malloc(iCounter * sizeof(random));
ran1_3ARG(&ran1_idum, &ran1_iy, ran1_iv);
dummy[0].idum = ran1_idum;
dummy[0].iy = ran1_iy;
memcpy(dummy[0].iv, ran1_iv, sizeof(ran1_iv));
for (i = 0; i < iCounter; i++)
ran1_3ARG(&dummy[i].idum, &dummy[i].iy, dummy[i].iv);
dummy[0].Anzahl = iCounter;
*random = dummy;
}
return iCounter;
}
here error:
a value of type "void *" cannot be assigned to an entity of type "RANDOMSTRUCT *"
Can anyone help me solve it?
Change the line:
dummy = malloc(iCounter * sizeof(random));
to say:
dummy = (RANDOMSTRUCT *)malloc(iCounter * sizeof(RANDOMSTRUCT));
dummy = malloc(iCounter * sizeof(random));
this allocates the wrong amount of memory (a multiple of a pointer size, not the pointed-to) and returns a void*. In c++ void* doesn't implicitly convert to other pointer types. In c it does.
Assuming you actually mean to use C-isms in C++ code, write this:
template<class T>
T* typed_malloc( std::size_t count = 1 ) {
return static_cast<T*>(malloc( sizeof(T)*count ));
}
this function is a type-safe version of malloc that handles 9999/10000 uses, and prevents an annoying class of bugs.
Then change the line of code to:
dummy = typed_malloc<RANDOMSTRUCT>(iCounter);
Sometimes using malloc in c++ isn't easy to remove, because your code interacts with c code. This kind of change can eliminate bugs before they happen as you modify c code to c++ relatively transparently.

Memory Error using lambda function with array

const int bookBoatNum = 10;
Wt::WPushButton *buttonBookBoat[bookBoatNum];
Wt::WDialog *dialogBookBoat[bookBoatNum];
for (int i = 1; i < bookBoatNum; i++){
dialogBookBoat[i] = new Wt::WDialog("Book Boat");
buttonBookBoat[i] = new Wt::WPushButton();
buttonBookBoat[i]->clicked().connect(std::bind([&dialogBookBoat,i]() {
dialogBookBoat[i]->show();
}));
}
The program compiles and runs. When I click on a WPushButton object, it crashes because of the third last line because of a memory error. This code works perfectly if buttonBookBoat and dialogBookBoat are single objects, rather than an array of objects. show() is a method that displays the dialog object.
Any help is appreciated, this error has been driving me crazy and my life is on the line with this code (not really).
const int bookBoatNum = 10;
Wt::WPushButton *buttonBookBoat[bookBoatNum];
Wt::WDialog *dialogBookBoat[bookBoatNum];
for (int i = 1; i < bookBoatNum; i++){
dialogBookBoat[i] = new Wt::WDialog("Book Boat");
Wt::WDialog * tempDialog=new Wt::WPushButton();
buttonBookBoat[i] = tempDialog;
buttonBookBoat[i]->clicked().connect(std::bind([tempDialog]() {
tempDialog->show();
}));
}
I think dialogBookBoat is an array so it will not exist after the function call.

C++ pointers and arrays

I have a problem with dynamic array.
In header file class i have this:
class CTerrain
{
...
CRock *rocks;
int numRocks;//=0
...
}
and in cpp i have this:
void CTerrain::Create()
{
numRocks = 0;
int NUM_ROCKS = rand()%10+1;
for(int i=0;i<NUM_ROCKS;i++)
{
rocks = new CRock;
numRocks++;
...
}
}
void CTerrain::Render()
{
for(int i=0;i<numRocks;i++)
rocks[i].render();//it works ok when here is 0 instead of 'i'
}
When I run this code I got error:
Unhandled exception at 0x00913aea in OpenGL.exe: 0xC0000005: Access violation reading location 0x1c00001f.
Thanks for any help, I have been trying to resolve this problem for like 4 hours...
EDIT:
Ok, so I changed Create() method to this:
void CTerrain::Create()
{
numRocks = 0;
int NUM_ROCKS = rand()%10+1;
rocks = new CRock[NUM_ROCKS];
for(int i=0;i<NUM_ROCKS;i++)
{
rocks[i].position = ...
numRocks++;
...
}
and also added delete [] rocks and now it's working.
Your Create function would be more like
void CTerrain::Create()
{
int NUM_ROCKS = rand()%10+1;
rocks = new CRock[NUM_ROCKS];
numRocks = NUM_ROCKS;
for(int i=0; i<NUM_ROCKS; i++)
{
rocks[i] = CRock{};
}
}
Just to add bit of explanation to above answer. Here:
for(int i=0;i<NUM_ROCKS;i++)
{
rocks = new CRock;
numRocks++;
...
}
What you do is, each time assign new instance of CRock to the pointer rock; thereby losing reference to the old object and creating memory leaks. Use a solution similar suggester by Cyber.
First off, rocks is pointer to CRocks. Your implemenation:
rocks[i].render() should be something like this:
rocks = new CRock [x]; (where x is the number of objects of type CRock.)
rocks[i] -> render().
delete rocks[i] // Just be sure to delete.
You may want to reference this for your solution on handling how a dynamic array of objects.
This other reference is good.
rocks = new CRock;
you overwrite CRock* pointer rocks in this line over and over again
Use this
rocks = new CRock[NUM_ROCKS];

memory overlapping in an initialization of a class

My problem is I have a header file in which I store all my classes and in my cpp file I have my initializations of these classes, the initialization is not dynamic I have a number of arrays of different classes.
Now the problem is when I started expanding the classes in my header, adding more members and methods,the initialization of 1 specific class start throwing assertions at me of memory overlapping and suggested using memmove() instead of memcpy(), though I use neither of them in that class.
I tried replacing this class with a downgraded version of it that worked in older versions of my source but it still threw the same assertion at me I don't know what part of the code is relevant here is the assertion is being asserted in the initialization of the class without any pointer to what exactly is wrong.
this is my initialization of the class :
Shuriken(cpFloat m,cpVect veloc,cpFloat elast,cpFloat myu) : Spark() , Bang1() , ShurikenFlame()
{
smass = m;
sv = veloc;
se = elast;
su = myu;
ToDraw = false;
Removed = true;
AllocatedBombAnim = false;
DrawFlamedShuriken = false;
DeployFlameBang = false;
PassedLine = false;
hitfruit = false;
FruitIsBeingHit = false;
ToRemoveBody = false;
DummyAdded = false;
HitBossBanana = false;
fruitnum = 11;//11 means it has no fruit
Sec_FlameCounter = 3;
LitShuriken_UVs[0] = CIwFVec2(0, 0);
LitShuriken_UVs[2] = CIwFVec2(1.0/4, 1.0/4);
LitShuriken_UVs[3] = CIwFVec2(1.0/4, 0);
LitShuriken_UVs[1] = CIwFVec2(0, 1.0/4);
Sparkle_UVs[0] = CIwFVec2(0, 0);
Sparkle_UVs[2] = CIwFVec2(1.0/2, 1.0/4);
Sparkle_UVs[3] = CIwFVec2(1.0/2, 0);
Sparkle_UVs[1] = CIwFVec2(0, 1.0/4);
lastPos = cpvzero;
lastAngle = 0;
struct cpVect initShurikenBody_Verts[35] =
{
cpv(-128.01,41.26),
cpv(-58.74,45.42),
cpv(-47.79,32.04),
cpv(-40.06,33.94),
cpv(-20.63,48.29),
cpv(-16.13,55.67),
cpv(-25.33,69.7),
cpv(0,134.67),
cpv(25.34,70.16),
cpv(16.14,55.67),
cpv(20.75,48.1),
cpv(39.98,34.04),
cpv(47.96,32.15),
cpv(58.86,45.38),
cpv(128.01,41.26),
cpv(74.55,-2.82),
cpv(57.95,1.45),
cpv(52.25,-5.19),
cpv(45.16,-26.79),
cpv(45.77,-35.34),
cpv(61.86,-41.64),
cpv(79.1,-108.95),
cpv(20.79,-71.41),
cpv(19.62,-54.33),
cpv(11.91,-51.14),
cpv(-12.02,-51.11),
cpv(-19.64,-54.26),
cpv(-20.81,-71.4),
cpv(-79.11,-108.95),
cpv(-61.87,-41.6),
cpv(-45.77,-35.03),
cpv(-45.18,-26.75),
cpv(-52.23,-5.35),
cpv(-57.88,1.31),
cpv(-74.48,-2.8),
};
struct cpVect initShurikenShape_Verts1[5] =
{
cpv(-128.01,41.26),
cpv(-58.74,45.42),
cpv(-47.79,32.04),
cpv(-57.88,1.31),
cpv(-74.48,-2.8),
};
struct cpVect initShurikenShape_Verts2[5] =
{
cpv(0,134.67),
cpv(25.34,70.16),
cpv(16.14,55.67),
cpv(-16.13,55.67),
cpv(-25.33,69.7),
};
struct cpVect initShurikenShape_Verts3[5] =
{
cpv(47.96,32.15),
cpv(58.86,45.38),
cpv(128.01,41.26),
cpv(74.55,-2.82),
cpv(57.95,1.45),
};
struct cpVect initShurikenShape_Verts4[5] =
{
cpv(79.1,-108.95),
cpv(20.79,-71.41),
cpv(19.62,-54.33),
cpv(45.77,-35.34),
cpv(61.86,-41.64),
};
struct cpVect initShurikenShape_Verts5[5] =
{
cpv(-79.11,-108.95),
cpv(-61.87,-41.6),
cpv(-45.77,-35.03),
cpv(-19.64,-54.26),
cpv(-20.81,-71.4),
};
struct cpVect initShurikenShape_Verts6[4] =
{
cpv(-47.79,32.04),
cpv(-40.06,33.94),
cpv(-52.23,-5.35),
cpv(-57.88,1.31),
};
struct cpVect initShurikenShape_Verts7[4] =
{
cpv(-20.63,48.29),
cpv(-16.13,55.67),
cpv(16.14,55.67),
cpv(20.75,48.1),
};
struct cpVect initShurikenShape_Verts8[4] =
{
cpv(39.98,34.04),
cpv(47.96,32.15),
cpv(57.95,1.45),
cpv(52.25,-5.19),
};
struct cpVect initShurikenShape_Verts9[4] =
{
cpv(45.16,-26.79),
cpv(45.77,-35.34),
cpv(19.62,-54.33),
cpv(11.91,-51.14),
};
struct cpVect initShurikenShape_Verts10[4] =
{
cpv(-12.02,-51.11),
cpv(-19.64,-54.26),
cpv(-45.77,-35.03),
cpv(-45.18,-26.75),
};
struct cpVect initShurikenShape_Verts11[10] =
{
cpv(-40.06,33.94),
cpv(-20.63,48.29),
cpv(20.75,48.1),
cpv(39.98,34.04),
cpv(52.25,-5.19),
cpv(45.16,-26.79),
cpv(11.91,-51.14),
cpv(-12.02,-51.11),
cpv(-45.18,-26.75),
cpv(-52.23,-5.35),
};
for(int i=0;i<5;i++)
ShurikenShape_Verts1[i] = initShurikenShape_Verts1[i];
for(int i=0;i<5;i++)
ShurikenShape_Verts2[i] = initShurikenShape_Verts2[i];
for(int i=0;i<5;i++)
ShurikenShape_Verts3[i] = initShurikenShape_Verts3[i];
for(int i=0;i<5;i++)
ShurikenShape_Verts4[i] = initShurikenShape_Verts4[i];
for(int i=0;i<5;i++)
ShurikenShape_Verts5[i] = initShurikenShape_Verts5[i];
for(int i=0;i<4;i++)
ShurikenShape_Verts6[i] = initShurikenShape_Verts6[i];
for(int i=0;i<4;i++)
ShurikenShape_Verts7[i] = initShurikenShape_Verts7[i];
for(int i=0;i<4;i++)
ShurikenShape_Verts8[i] = initShurikenShape_Verts8[i];
for(int i=0;i<4;i++)
ShurikenShape_Verts9[i] = initShurikenShape_Verts9[i];
for(int i=0;i<4;i++)
ShurikenShape_Verts10[i] = initShurikenShape_Verts10[i];
for(int i=0;i<10;i++)
ShurikenShape_Verts11[i] = initShurikenShape_Verts11[i];
for(int i=0;i<35;i++)
ShurikenBody_Verts[i] = initShurikenBody_Verts[i];
}
I am using Visual Studio 2010 with Marmalade SDK and I am writing in C++.
Thanks for any help,
Anton
Ok, so if we assume that ShurikenShape_Verts1 is either a regular C style array or a C++ style std::array and has the type cpVect, and cpVect is a POD struct:
for(int i=0;i<5;i++)
ShurikenShape_Verts1[i] = initShurikenShape_Verts1[i];
can be copied as:
memcpy(ShurikenShape_Verts1, initShurikenShape_Verts1,
sizeof(initShurikenShape_Verts1));
However, I have made some assumptions here, since you haven't posted enough code. I'd hate to start a "can post this, can you post that" type thread, asking for a large number of other bits of your code, but it also means that I may not have answered the question correctly, since I don't know for sure that your cpVect is indeed a POD struct, for example.
(I'd submit a comment but I don't have enough of a stackoverflow "reputation" to do so:-()
I would seriously stand back and look at why you are trying to copy this stuff to start with. Copying lots of stuff is comparatively slow. Far better to use a pointer to the existing array or a reference, which depends on your style.
If by "cpVect is just 2 floats made into a vector" you mean vector, then don't use memcpy or whatever. This is just going to give you heap issues later. Remember that these work by allocating behind the scenes. If you use memcpy you are going to get two objects pointing to the same content, and when the first goes out of scope that content will be freed.

Member variables of a object get overridden when creating another object in the object

I have a memory issue with a class of mine. The issue occurs when I create an object in a member function of a class. It is about the class below. I removed the member functions because they aren’t necessary:
class User
{
private:
bool locked;
bool active;
std::vector<City> * userCitys;
UserData userData;
Credentials credentials;
The problem occurs when I call this function:
int User::addCity(CityData cityData)
{
lockUserObject(); //Everything is fine here
City cityToAdd; //When this object is created, the memory of userCitys will get overridden
cityToAdd.activate();
userCitys->push_back(cityToAdd);
int cityID = userCitys->size() - 1;
userCitys->at(cityID).editCityData(cityData);
unlockUserObject();
return cityID;
}
In the first place I created userCitys on the stack. For test purpose I placed it on the Heap. The address of userCitys get overridden by some data. I can’t find the problem. the City is just a basic class:
Part of the header:
class City
{
private:
bool active;
Supplies supplies;
std::vector<Building> buildings;
std::vector<Company> companies;
std::vector<Share> shares;
std::vector<Troop> troops;
CityData cityData;
Constructor:
City::City()
{
active = false;
}
How is it possible that userCitys get overridden? This all happens on a single Thread so that can’t be a problem. I tried a lot of thing, but I can’t get it to work. What is the best approach to find the problem?
Edit:
Lock function:
void User::lockUserObject()
{
for( int i = 0; locked ; i++)
{
crossSleep(Settings::userLockSleepInterval);
if( i >= Settings::userLockMaxTimes )
Error::addError("User lock is over userLockMaxTimes",2);
}
locked = true;
}
I call the code here (Test function):
City * addCity(User * user)
{
Location location;
location.x = 0;
location.y = 1;
CityData citydata;
citydata.location = location;
citydata.villagers = 0;
citydata.cityName = "test city";
int cityID = user->addCity(citydata); //addCity is called here
City * city = user->cityAction(cityID);;
if( city == NULL)
Error::addError("Could not create a city",2);
return city;
}
The add user (Test code):
User * addUser()
{
UserData test;
test.name = "testtest";
Credentials testc("testtest",3);
//Create object user
int userID = UserControle::addUser(test,testc);
User * user = UserControle::UserAction(userID);
if( user == NULL)
Error::addError("Could not create a user",2);
return user;
}
My test function:
void testCode()
{
User * user = addUser();
City * city = addCity(user);
}
This function in called in main:
int main()
{
testCode();
return 0;
}
Here are UserAction and addUser in UserControle:
int UserControle::addUser(UserData userdata, Credentials credentials)
{
int insertID = -1;
for( int i = 0; i < (int)UserControle::users.size(); i++)
{
if( !UserControle::users.at(i).isActive() )
{
insertID = i;
break;
}
}
User userToInsert(userdata,credentials);
if( insertID != -1 )
{
UserControle::users.insert( UserControle::users.begin() + insertID,userToInsert);
return insertID;
}
else
{
UserControle::users.push_back(userToInsert);
return UserControle::users.size() - 1;
}
}
User* UserControle::UserAction(int userID) //check all indexes if greater then 0!
{
if( (int)UserControle::users.size() <= userID )
{
Error::addError("UserAction is out of range",3);
return NULL;
}
if( !UserControle::users.at(userID).isActive())
{
Error::addError("UserAction, the user is not active.",3);
return NULL;
}
return &UserControle::users[userID];
}
There's a few things you could try:
Remove code until the fault goes away. In other words, distill a minimal example from your code. I guess you'll then see the error yourself, otherwise post that small example program here and others will.
Don't use raw pointers. The question with those is always who owns what they point to. Use smart pointers instead, e.g. unique_ptr (C++11) or auto_ptr (C++98) for exclusive ownership.
If you have pointer members like "userCities", you need to think about what happens when copying instances of that class (you already wrote a proper destructor, or?). So, either prevent copying (make copy-constructor and assignment operator private and without implementing it) or implement them in a way that the vectors are properly cloned and not shared between different instances.
Don't use C-style casts. If those are necessary to get anything through the compiler, the code is probably broken.