July 13th, 2009, 5:25 pm
Hi kevin,It looks like, because kevin called this a brainteaser, it became far more complicated than what it actually is. Also, everytime C++ guys talk about char* it's like taking care of the Devil itself. But without bothering what the heap or stack are or how and why we should use delete[], we could just say delete only what YOU allocated (either from a direct call to new or using a function that does so).When you call f1 using f1("will I leak?"), the system allocates a temporary variable, puts "will I leak?" in it, calls f1 with it, and deallocates it when f1 returns. So no memory leak issue here and you don't have the right to alter/delete str in f1.Now, for the reason why Cuch could (and did) call delete on str in f1A (V2 version) was not because it's a string which is a super-smart C++ thing that uses an internal heap and so and so: it was just because str was a pointer that Cuch allocated himself before calling f1A. No? Try calling f1A (in V2, with the call to delete) this way:{ string chh("dddddd"); f1A( &chh );}And mister Cuch was king enough, once he knew that now you know why you should not play with unwanted pointers, to provide the best version: V3.Cheers