Deleting from vector

I have a vector as a private member variable of a class:
std::vector<const char*> strings;

Trying to delete them during the destructor:
1
2
3
4
5
{
  std::vector<const char*>::iterator iter;
  for (iter = strings.begin(); iter != strings.end(); iter++)
    delete [] *iter;
}


I'm triggering a break point though. Any ideas? Thanks.

Edit: And it also doesn't work when it's just a vector<char*>
Last edited on
How did you create the const char* originally, and how did you put it into the vector?
Last edited on
1
2
3
4
5
void StringTable::addString(const char* str)
{
	char * newStr = new char[myStrlen(str)];
	strings.push_back(myStrcpy(newStr, str));
}


I can cout the c-strings just fine when I access the vector.


Edit: Oh Moschops, that needs to be char * newStr = new char[myStrlen(str) + 1]; :), thanks.
Last edited on
Usually something bad happen on delete when it has already been deleted (or the memory has simply been trashed, writing over whatever system the compiler is using to keep track of allocated memory). Is there any code elsewhere doing a delete of this block of memory?

This is begging to be run through valgrind, which would keep track of it for you and tell you where it goes wrong. Can that be done?
Last edited on
Once I changed the new to give room for the null terminator, things are working just fine.
That's interesting; presumably you were overrunning and trashing the memory at the start of the next block, which is traditionally where the new/delete crib is hidden.
This breaks at the delete too:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string.h>


int main(void)
{
	const char* str = "Hello World";
	char* str2 = new char[strlen(str)];

	strcpy(str2, str);
	
	delete [] str2;

	return 0;
}


but not when line 7 has the " + 1 ". At least string.h functions are just as dangerous as mine :)

myStrcpy:
1
2
3
4
5
6
7
8
9
10
11
12
char* StringTable::myStrcpy(char* dest, const char* source)
{
	char * pos = dest;
	while (*source)
	{
		*dest = *source;
		++dest;
		++source;
	}
	*dest = *source;
	return pos;
}

If dest is way too short, then it's a bad memory allocate during the copying. If dest is one too short, it's a break during deletion.
Last edited on
Topic archived. No new replies allowed.