Way to tell what delete is doing?

Member
Posts: 49
Joined: 2006.07
Post: #1
Is there some way of getting the debugger to tell me comprehensively what a call to delete in C++ is doing?
I have a C string on the heap, addressed by a pointer called prompt, and when I call "delete [] prompt" or "delete prompt," (I'm not sure which I'm meant to use) one of my other variables gets a 0 written over it. Perhaps related, is it safe to use strdup in C++?
Anyway, I know that the C string and my other data don't actually share the same location in memory, because modifying one does not modify the other, and I have printed out their addresses with cout, so I am trying to figure out why delete is erasing both of them.
Quote this message in a reply
Moderator
Posts: 697
Joined: 2002.04
Post: #2
'delete' deletes a single object, 'delete []' deletes an array of objects; if you created your C string by means of 's = new char [s_length];', you should call 'delete []', if by means of malloc() or friends, you should call free().

Mark Bishop
--
Student and freelance OS X & iOS developer
Quote this message in a reply
Member
Posts: 49
Joined: 2006.07
Post: #3
I made it using strdup, so I imagine I should call free(), but free doesn't like that it's const. Is there a problem with just casting it non-const? Thanks.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #4
There is no problem casting it to non-const, though if it's meant to be changed (or freed), it shouldn't be const in the first place.
Quote this message in a reply
Member
Posts: 49
Joined: 2006.07
Post: #5
Well it's a const char *, so my understanding was that the chars it points at can't be changed, but the pointer itself can. Shouldn't I be able to change what it points at, e.g., by calling strdup? I could see running into trouble if it were a char const * or a const char const *, but even then I don't know why it would free things it doesn't even own. Now that I've done more test runs it turns out that even calling strdup occasionally overwrites memory that was already allocated with operator new. Does xcode have issues with linking and memory allocation, ie could it be that one of my .cpp files is not respecting another .cpp file's claim to allocated memory?
Quote this message in a reply
Member
Posts: 49
Joined: 2006.07
Post: #6
My specific issue with the const char * mysteriously resolved itself when I got rid of some other variables, but should it resurface again, I'd still like to know if anyone knows of a way of seeing what specific memory addresses are being modified by a call to delete/free. Thanks.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #7
If you're freeing a pointer, you are changing the data it points to: you're deleting it!
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  C++: is "delete (base_class*)this;" safe? sealfin 3 3,191 May 16, 2008 03:26 PM
Last Post: sealfin