calling delete on pointer after sprintf causes crash

Hi,

I don't understand why this causes a crash, can anyone explain?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

void func()
{
	while(1)
	{
		char *string = new char;
		sprintf(string, "this is a test %d", 1);
		
		printf("%s\n", string);
		delete string;
	}
}

int main()
{
	func();
}


The crash occurs after the call to delete, I'm not sure why? I was trying to prevent a memory leak as the code is executed in a loop. When running in the debugger Windows steps in and tells me that a likely cause is corruption in the heap, but I can't see why what I'm doing causes this?

Cheers for any help.
You have allocated space for a single character, which can hold no more than the terminating null of a C string - in other words, an empty string.
What Athar said.
Use new[] and delete[]: http://www.cplusplus.com/doc/tutorial/dynamic/
That makes sense thanks for the quick replies!
Topic archived. No new replies allowed.