c++ - CStrings and pointers: Heap corruption when trying to delete a character array -
i've exhausted myself googling this, haven't been able find clear answer or myself understand going wrong. part of homework assignment, i'm trying dynamically allocate memory character array (ie. cstring) , assign char pointer variable point @ it, delete allocated memory before end program. i'm wrapping head around pointers suspect of understanding of what's happening behind scenes not correct, , i'm ending visual studio 2010 giving me heap corruption breakpoints.
here's simplified version of i'm trying (my comments indicate think i'm doing):
char *chptr = new char[10]; // create char pointer type variable, , point @ memory allocated char array of length 10 chptr = "september"; // assign 9 characters (+1 null terminator character) char array cout << chptr; // prints "september", finds null terminator , stops printing delete [] chptr; // causes heap corruption -> don't know why. shouldn't delete array of memory chptr pointing at?
- i've tried using
delete chptr
well, same heap corruption result. - i've tried manually assigning null terminator end of array
chptr[9] = '\0';
, results in heap corruption. why? can access individual characters within array when thingscout << chptr[7];
etc without problems...
what's confusing works without error:
char *chptr = new char[10]; // above, create char pointer type , point @ memory allocated char array of length 10 delete chptr; // doesn't give error!
it seems initializing array assigning value breaking things me somehow.
can me out?
this source of problem:
char *chptr = new char[10]; // create char pointer type variable, , point @ memory allocated char array of length 10 chptr = "september";
first allocate heap memory on chptr
, allocate non-heap memory (data segment memory, if precise) assigning non-heap char array value of "september" on it.
you try delete non-heap memory , error get.
use strcpy(chptr,"september")
or better : lose c , use std::string
.
Comments
Post a Comment