valgrind malloc error, pointer being freed was not allocated

==39800== Invalid free() / delete / delete[] / realloc()
==39800== at 0x4D9D: free (vg_replace_malloc.c:477)
==39800== by 0x10000C471: Tokenizer::~Tokenizer() (in ./a.out)
==39800== by 0x10000C424: Tokenizer::~Tokenizer() (in ./a.out)
==39800== by 0x100001B8B: main (in ./a.out)
==39800== Address 0x10002a778 is 8 bytes inside a block of size 7,208 alloc'd
==39800== at 0x47F1: malloc (vg_replace_malloc.c:300)
==39800== by 0x4928D: operator new(unsigned long) (in /usr/lib/libc++.1.dylib)
==39800== by 0x10000888E: Tokenizer::Tokenizer(std::__1::basic_istream<char, std::__1::char_traits<char> >&) (in ./a.out)
==39800== by 0x10000808C: Tokenizer::Tokenizer(std::__1::basic_istream<char, std::__1::char_traits<char> >&) (in ./a.out)
==39800== by 0x100001198: main (in ./a.out)

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
Tokenizer::Tokenizer(istream& inputStream) : instream(inputStream){
	//read entire data into memory
	string tempf;
	tempf = string((std::istreambuf_iterator<char>( instream )),
            (std::istreambuf_iterator<char>()) );
	istringstream stream(tempf);
	lines = new string[300];
	//read a line
	string temp;
	getline(stream, temp);
	lines[0] = temp;
	for(int i = 1; i < 301; i++){
		getline(stream, temp);
		string firstValue;
		istringstream instr(temp);
		getline(instr, firstValue , ',');
		lines [i] = temp;
		if(firstValue == "-1"){
			break;
		}
	}
	point = 0;
	istringstream streamWord(lines[point]);
	transaction = readToken(streamWord);
}
Last edited on
The stack trace shows the problem is in your Tokenizer destructor.

However, since you posted the constructor, there is also a problem there. lines points to a dynamic array of 300 string elements. Valid indexes for the array are 0 to 299, however in your for loop you use the invalid index 300 resulting in undefined behavior.

Last edited on
One thing I see is this:

1
2
3
4
5
6
7
8
// line 7
lines = new string[300];  // <- array of size 300, meaning [299] is last valid index

// line 12
for(int i = 1; i < 301; i++){  // <- i will == 300

// line 17
lines [i] = temp;  // <- OUT OF BOUNDS when i==300 
thank you so much for point that out. not sure what is wrong with my destructor as it's simply deleting and null out the pointers.
1
2
3
4
5
6
Tokenizer::~Tokenizer(){
	delete[] lines;
	delete[] token;
	token = NULL;
	lines = NULL;
}
Last edited on
You don't have any member, token, that is assigned a value in the constructor.
Topic archived. No new replies allowed.