I've exhausted myself googling this, but I haven't been able to find a clear answer or help myself understand what is going wrong. As part of a homework assignment, I'm trying to dynamically allocate memory for a character array (ie. a CString) and assign a char pointer variable to point at it, then delete the allocated memory before I end the program. I'm just wrapping my head around pointers so I suspect that some of my understanding of what's happening behind the scenes is not correct, and I'm ending up with Visual Studio 2010 giving me heap corruption breakpoints.
Here's a simplified version of what I'm trying to do (my comments indicate what I think I'm doing):
char *chPtr = new char[10]; // Create a char pointer type variable, and point it at the memory allocated for a char array of length 10
chPtr = "September"; // Assign 9 characters (+1 null terminator character) to the char array
cout << chPtr; // Prints "September", then finds the null terminator and stops printing
delete [] chPtr; // THIS is what causes my heap corruption -> But I don't know why. Shouldn't this delete the array of memory that chPtr is pointing at?
- I've tried using
delete chPtr
as well, with the same heap corruption result. - I've tried manually assigning a null terminator to the end of the array
chPtr[9] = '\0';
, but this also results in heap corruption. Why? I can access individual characters from within the array when I do things likecout << chPtr[7];
etc without any problems...
What's really confusing is that this works without error:
char *chPtr = new char[10]; // As above, create a char pointer type and point it at the memory allocated for a char array of length 10
delete chPtr; // This doesn't give any error!
It seems that initializing the array by assigning a value is breaking things for me somehow.
Can anybody help me out?