Vector Inventory problem

i have a vector based inventory implemented pretty well; however i keep running into a pretty large problem. when i click an item depending on where it is in the vector i get an access violation in the vector range and the game crashes. here is how my inventory works and the basic code for it;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
struct Items
{
 //more attributes but here is the idea
 char *name;
 int amnt;
 char *type;
 int price;
};

class UserInterface
{
public:
std::vector<Items*> items;
UserInterface() {} //not so important stuff just initializing vars
~UserInterface() {} // exactly what you would expect deleting (items) elements
void AddItem(char *name, int amnt, char *type, int price)
{
 for(unsigned i = 0; i <items.size(); i++)
  {
   if(items[i]->name == name)
    {
      items[i]->amnt += amnt
    }
   else
    { 
      Item *item = new Item(); //is this wrong for a structure?
      item->name = name; //... and so on for the struct
      items.push_back(item);
    }
  }
}
void Update()
{
  if(keypressed==true && inInventory==false && timer==0)
  {
    inInventory = true;
    timer = 10;
  }
  if(keypressed==true && inInventory==true && timer==0)
  {
    inInventory = false;
    timer = 10;
  }
  if(inInventory==true)
  {
    if(timer>0) timer--; 
    for(unsigned i = 0; i<items.size(); i++)
    {
      if(isPressed(x,y*i,width,height,items[i]->name,items[i]->amnt,items[i]->type,items[i]->price)==true)
      {

         timer = 10; //delay for button pressing      

        if(items[i]->name=="Health Potion")
        {
          PlayerHealth+=items[i]->damage; // i know its not a member but its the idea 
          items.erase(items.begin() + i); // this is where i get the error. i know im doing something wrong
        }
        if(items[i]->type=="Armor")
        {
          PlayerArmor+=items[i]->damage; // i know its not a member but its the idea 
          items.erase(items.begin() + i); // this is where i get the error. i know im doing something wrong
        }
      }
    }
  }
}
protected:
bool inInventory;
int timer;
};
Last edited on
Line 20,54,59: You can't compare char arrays that way. You're comparing addresses, not strings. Use std::string or if you insist on using C rather than C++, use strcmp.

Line 27: You can't copy char arrays that way. Use std::string or if you insist on using C rather than C++, use strcpy.

Line 59: I don't see where you've initialized items[i]->type. Reference to an uninitialized pointer is going to cause an access violation. Ditto remarks regarding std::string vs. char *.




Oh okay I didn't know that thank you that's probably part of the problem. Also in my actual class the addItem() initializes all of the data members in Item. I keep getting out of range errors would that be from comparing char arrays to strings?
Im going to go ahead and post all of the code from the inventory class. I changed the comparison to strcmp and used strcpy() instead of assigning a string to a char array. i am still getting the error. can someone please help me idk what i am doing wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#include "darkgdk.h"
#include <vector>
#include "constants.h"
#include <string.h>
#ifndef UI_H
#define UI_H

struct Item
	{
		char name[30];
		int img;
		int amnt;
		int health;
		char type[30];
		int damage;
		int price;

	};
class UI
{
public:
	
	std::vector<Item*> items;
	std::vector<Item*>::iterator Itemit;
	

	UI() 
	{
		//active objects
		WS = false;
		SA = false;
		SPA = false;
		drop = false;
		FireScrollisActive = false;
		WepTimer = 0;
		
		
		

		
		
		
		
		
		
		inTimer=0;
		inMenu=false;
	}
	~UI() {}

	void AddItem(char name[30],int img, int amnt, int health, char type[30], int damage, int price)
	{

		bool same=false;
		unsigned p;

		for(unsigned i = 0; i< items.size(); i++)
		{
			
			if(items[i]->name == name && (items[i]->type!="Weapon" || items[i]->type!="Armor"))
			{
				same = true;
				p = i;
			}
		}
		if(same==false)
		{
			if(items.size()<MAX_ITEMS)
			{
				Item *ITEMS = new Item();
				strcpy(ITEMS->name,name);
				ITEMS->img = img;
				ITEMS->amnt = amnt;
				ITEMS->health = health;
				strcpy(ITEMS->type,type);
				ITEMS->damage = damage;
				ITEMS->price = price;
				items.push_back(ITEMS);
			}
			if(items.size()==MAX_ITEMS)
			{
				message.Message("inventory full");
				dbPlaySound(ERRORS);
			}
		}else
		{
			items[p]->amnt = items[p]->amnt + amnt;
		}
			
		
			
		
		

	}
	int IMGButton(int x, int y, int width, int height, int img, char text[30], int amt,char type[30], int damage, int price)
	{
		

		dbPasteImage(ITEMBAR,x,y,1);
		dbPasteImage(img,x+10,y,1);
		if(dbMouseX()>x && dbMouseY()>y && dbMouseX()<x+width && dbMouseY()<y+height)
		{
			dbPasteImage(ITEMBARS,x,y,1);
			dbPasteImage(img,x+10,y,1);

			
		
			
			if(dbMouseClick()==1)
			{
				return 1;
			}
		}
		dbSetTextSize(32);

		dbCenterText(x+256,y,text);
			dbSetCursor(x+460,y);
			dbPrint(amt*1.0);

			dbInk(dbRGB(255,255,77),dbRGB(0,0,0));	
		dbSetCursor(x+40,y);
		dbPrint(price*1.0);
		dbInk(dbRGB(255,255,255),dbRGB(0,0,0));

		if(type=="Weapon")
		{
		dbInk(dbRGB(255,0,0),dbRGB(0,0,0));
		dbSetCursor(x+420,y);
		dbPrint(damage*1.0);
		dbInk(dbRGB(255,255,255),dbRGB(0,0,0));
		}
		if(type=="Armor")
		{
		dbInk(dbRGB(34,185,255),dbRGB(0,0,0));
		dbSetCursor(x+420,y);
		dbPrint(damage*1.0);
		dbInk(dbRGB(255,255,255),dbRGB(0,0,0));
		}
		return 0;

	}

	void WEPHandle()
	{
		if(WepTimer>0) 
		{
			WepTimer--;
		}
		if(dbMouseClick()==1 && WepTimer ==0 && UI::inMenu==false)
		{
			WepTimer=20;
		}
		
		if(WS==true)
		{
			
			dbShowObject(WSWEP);
			dbHideObject(SAWEP);
			dbHideObject(SPAWEP);

			if(WepTimer >10) 
			{
				dbPitchObjectDown(WSWEP,15);
			
			}
			if(WepTimer>0 && WepTimer<=10)
			{
				dbPitchObjectUp(WSWEP,15);
			
			}

		}
		if(SA==true)
		{
			
			dbShowObject(SAWEP);
			dbHideObject(WSWEP);
			dbHideObject(SPAWEP);

			if(WepTimer >10) 
			{
				dbPitchObjectDown(SAWEP,15);
			
			}
			if(WepTimer>0 && WepTimer<=10)
			{
				dbPitchObjectUp(SAWEP,15);
			
			}
		}
		if(SPA==true)
		{
			
			dbShowObject(SPAWEP);
			dbHideObject(SAWEP);
			dbHideObject(WSWEP);

			if(WepTimer >10) 
			{
				dbPitchObjectDown(SPAWEP,15);
			
			}
			if(WepTimer>0 && WepTimer<=10)
			{
				dbPitchObjectUp(SPAWEP,15);
			
			}
		}
	}
	void Update()
	{
		
		//health hud
		WEPHandle();
		if(PlayerHealth>MAX)
		{
			PlayerHealth = MAX;
		}
		if(FireScrollisActive==true)
		{
			dbPasteImage(FIREA,0,dbScreenHeight()-128,1);
			if(dbMouseClick()==1 && inTimer==0)
			{
				dbPositionObject(MAGIC,dbCameraPositionX(),dbCameraPositionY()-5,dbCameraPositionZ());
				dbRotateObject(MAGIC,dbCameraAngleX(),dbCameraAngleY(),dbCameraAngleZ());
				inTimer=15;
				FireScrollisActive = false;
			}
		}
		dbMoveObject(MAGIC,15);
		dbRollObjectLeft(MAGIC,2);
		for(int x = 0; x < (PlayerHealth/10); x++)
		{
			dbPasteImage(HEALTHHUD,(x*64)+25,10,1);
		}
		for(int x = 0; x < (PlayerArmor/10); x++)
		{
			dbPasteImage(ARMOR,(x*32)+25,75,1);
		}

		
		if(inTimer>0) inTimer--;
		if(inTimer == 0 && inMenu == false && dbKeyState(15)==1)
		{
			Pause = true;
			inMenu = true;
			inTimer = 20;
		}
		if(inTimer == 0 && inMenu == true && dbKeyState(15)==1)
		{
			Pause = false; 
			inMenu = false;
			inTimer = 20;
		}
		if(inMenu==true)
		{
			if(inTimer>0) inTimer--;
			dbPasteImage(DROP,0,dbScreenHeight()-128,1);
			if(drop==true) dbPasteImage(DROPT,0,dbScreenHeight()-128,1);

			if(dbMouseX() > 0 && dbMouseY() > dbScreenHeight()-128 && dbMouseX() < 128 && dbMouseY() < dbScreenHeight()+128)
			{
				dbPasteImage(DROPT,0,dbScreenHeight()-128,1);
				if(dbMouseClick()==1 && drop == false && inTimer==0)
				{
					drop = true;
					inTimer = 20;
				}
				if(dbMouseClick()==1 && drop == true && inTimer==0)
				{
					drop = false;
					inTimer = 20;
				}
			}
			dbSetTextSize(64);
			dbCenterText(dbScreenWidth()/2,dbScreenHeight()/2-400,"Inventory");
			dbSetTextSize(32);
			dbPasteImage(MAININV,(dbScreenWidth()/2)-256,(dbScreenHeight()/2)-(336),1);
			for( unsigned i = 0; i < items.size(); i++)
			{
				if(IMGButton((dbScreenWidth()/2) - 246,(dbScreenHeight()/2)-326+(i*32),492,32,items[i]->img,items[i]->name,items[i]->amnt,items[i]->type,items[i]->damage,items[i]->price)==1 && inTimer ==0)
				{
					if(drop==false)
					{
						
						if(strcmp(items[i]->name,"Health Potion")==0)
					{
						if(PlayerHealth < MAX)
						{
							PlayerHealth += items[i]->damage;
							if(items[i]->amnt>1) items[i]->amnt--;
							if(items[i]->amnt==1) items.erase(items.begin() + i);
							dbPlaySound(POTION);
						}
						if(PlayerHealth == MAX)
						{
							message.Message("Health Full");
							dbPlaySound(ERRORS);
						}
					}
						if(strcmp(items[i]->type,"Armor")==0)
					{
						dbPlaySound(EQUIP);
						PlayerArmor += items[i]->damage;
						message.Message("Item Equiped");
						items.erase(items.begin() + i);
						
					}
						if(strcmp(items[i]->name,"Fire Scroll")==0)
						{
							//message.Message("used fire scroll");
							
							FireScrollisActive=true;
							items.erase(items.begin() + i);
							
						}
					inTimer=10;
				}
					if(drop==true) 
				{
					message.Message("Item(s) Dropped");
					items.erase(items.begin() + i);
					inTimer = 20;
				}
				}
				
			}
		}
		
		
	}

	bool isInMenu()
	{
		return inMenu;
	}

protected:
	bool inMenu;
	int inTimer;
	int WepTimer;
	bool WS;
	bool SA;
	bool SPA;
	bool FireScrollisActive;
	bool drop;
	

};
#endif 


its very strange almost all of the items work, but sometimes i get this error...

from the vector class
1
2
3
4
5
#endif /* _HAS_ITERATOR_DEBUGGING */
		_SCL_SECURE_VALIDATE_RANGE(_Pos < size());

		return (*(_Myfirst + _Pos));
		}


usually its when i click the last item in the inventory though but not always.
Line 60,126,133: You're still comparing pointers, not the contents of the char array.

If you're going to be writing C++, use the C++ idiom for strings (std::string) rather than C strings. They're easier and safer.

On a related note why does your class have a vector<Item*> instead of a vector<Item>.

I see where you allocate memory with new for this vector, but I don't see where you're deallocating the memory with delete. Looks like a fairly big memory leak.


On line 293 you erase an item in the vector. You then continue on to use the same index. If that item is the last item in the array, this is undefined behavior.

If it isn't, you still have a pretty large hole in your logic. It is possible to erase 3 items from your inventory for each iteration of the loop if the order of the items is amenable. If you erase an item, decrement i and continue. Also, use if/else where appropriate.

Last edited on
Thank you cire. Now that you pointed that out it makes complete since for why its behaving the way it is. I am changing the struct Item to a class to gain more control over the items in the inventory. I will post the working code to see if you guys have any suggestions. This is such a great community for programmers. I appreciate all of your guys help.
Topic archived. No new replies allowed.