Sign in to follow this  
zix99

std::vector causing Illegal Instruction...

Recommended Posts

Hello everyone I'm thinking that vectors werent meant for this kind of use, but I'm getting an illegal instruction every time I use a vector to hold a class pointer, and then try to delete a single class pointer within the vector. Code: (Example)
//Test for the illegal instruction vector error

#include <vector>
using namespace std;


class HoldingClass{
public:
	long number_of_something;
	char *buffer;
	inline long GetSize(){return number_of_something;}
private:
	bool active;
};


vector <HoldingClass*> test;


HoldingClass *MakeClass(){
	HoldingClass *n_class = new HoldingClass;
	test.push_back(n_class);
	return n_class;
}

void DeleteClass(HoldingClass *id){
	test.erase(&id);
	delete id;
}



int main(){
	HoldingClass *temp;
	temp=MakeClass();

	//bla bla bla..

	DeleteClass(temp);

	return 0;
}


If this case is known and unfixable, is there a different container type to hold this type of data, or do I have to fall back to dynamic arrays. Thanks for your help ~zix~

Share this post


Link to post
Share on other sites
You're storing HoldingClass *. You're passing a HoldingClass ** to vector.erase(). That's not what you want.

[edit: and indeed, there's not even a member erase for vector, you'll need to fetch an iterator first, or change the design to accept an iterator, not a pointer.]

Share this post


Link to post
Share on other sites
The problem is that you are trying to erase an element that doesn't exist. When you try erase(&id) it tries to turn &id into an iterator, but it happens to point to an location on the stack. This causes mad muju to happen. What you need to do is search the vector for the element you want to earse and then call erase() with a real iterator, and not the address of the pointer on the stack.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this