The African Chief wrote:
Procedure StrDispose ( Str : PChar ); Begin If ( Str <> Nil ) and ( Str^ <> Chr ( 0 ) ) then begin Free ( Str ); Str := Nil; { doesn't seem to do anything !!!} end; End; {* StrDispose *}
Obviously, the line "Str := Nil" does not actually set it to Nil. I would have to make "Str" a VAR parameter to do this,
You seem to answer your own question here. Of course, Str, being a value parameter, will not be set to Nil, you couldn't expect this... ;-)
but I don't want to that (it will become incompatible with BP for one).
Yes, BP uses a value parameter, too, and doesn't try to set the pointer to Nil. So my question in the first place is, why do you want the pointer to be set to Nil? I think, with careful programming, you shoudln't ever access the value of a StrDispose'd pointer. (And if this could happen, setting it to Nil manually when necessary seems like a good way to solve the problem, in BP as well as in GPC.)
I have now done a hack to make sure that "Str" points to nothing, by inserting this line; Str^ := #0; before the call to "Free ( Str )". Is there any reason why I shouldn't do this?
Well, it's, of course, perfectly legal to do this... but unfortunately it will not do what you expect it to do. The memory that's free'd is still undefined, whether you write something into it or not. Maybe the free() call doesn't usually overwrite the memory at once, but perhaps sometimes, e.g. when memory is returned to the system. Maybe (even probably) it behaves differently on different platforms, or with the next version of GPC, libc, the kernel or whatever, who knows?
Therefore, I'd consider it bad practice to do what you intend to do, since it will tend to hide errors in the calling program, i.e. errors may not happen to show up during debugging, but will show in the delivered program, thanks to Murphy. I don't think that's what you want.
I'd rather even change the routines to write *bad* values into the area so that errors will show up as early as possible. (Doing this is a bit difficult here, since you don't know the size of the memory block, so it might not be worth the effort here...)