Getting exception CrtIsValidHeapPointer

I've been trying out exercises from Stroustrup's PPP book. I've stumbled upon some errors and I dont understand why it is happening.

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
  #include <iostream>

char* strdupl(const char* r)
{
	int len = 0;
	const char* tempar = r;
	while (*tempar++) len++;			//Get length of chars.

	char* dup = new char[len + 1];	//Create an array
	char* dup_ptr = dup;			//Pointer to array
	while (*r) *dup_ptr++ = *r++;	//Copy args to array

	*dup_ptr = 0;					// adds '\0' to dup
	return dup;
}

int main()
{
	char arr1[] = "test" ;
	char* dupl = strdupl(arr1);

	while (*dupl) std::cout << *dupl++;
	delete[] dupl;						// deallocate dupl

	return 0;
}


If I try to deallocate dupl, my program triggers an exception _CrtIsValidHeapPointer.
Last edited on
Line 23: This pointer is no longer equal to what new[] gave you, because of the loop on line 22.
Ah i see. Thanks alot for pointing it out, silly oversight by me.
Topic archived. No new replies allowed.