Sunday, August 2, 2009

Why do i always get an error when deleteing a char*?

int main(){


char* p = new char[20];


p = "foobar";





delete[] p;


}





this always produces a runtime error:


"Windows has triggered a breakpoint in test2.exe.





This may be due to a corruption of the heap, and indicates a bug in test2.exe or any of the DLLs it has loaded."





i'm using visual c++ express edition..

Why do i always get an error when deleteing a char*?
The previous answerer is correct. You need to understand how C strings work to decipher this problem. When you use new, p points to a valid memory location. When you assign p = “foobar”, “foobar” is created in another memory location. Then p is pointed to that other memory location.





Do you see the problem yet? You create memory with new, but you lose the pointer to it. You reassign the pointer to string literal, which is at another memory location.





Delete won’t work on a string literal. So you have two problems. You’re attempting to delete memory you never dynamically allocated. And because you lost the original memory address, you can’t free that up either.





The solution is to strcpy or strncpy foobar into p. You cannot use assignment. You may also want to look into C++ strings. The interface allows for more logical usage such as assignment directly, and comparisons.
Reply:use strcpy(p,"foobar");

gladiolus

No comments:

Post a Comment