0

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.

Barcio77
  • 36
  • 8
  • I still have error after changing to "CRock **rocks". Now it shows up in line: "rocks[i] = new CRock;" Error: Unhandled exception at 0x00293b7a in OpenGL.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd. – Barcio77 Apr 06 '15 at 20:30

4 Answers4

1

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{};
    }
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0
rocks = new CRock;

you overwrite CRock* pointer rocks in this line over and over again

Use this

rocks = new CRock[NUM_ROCKS];

Sly_TheKing
  • 518
  • 7
  • 14
0

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.

Community
  • 1
  • 1
penguin2718
  • 464
  • 1
  • 3
  • 7