Page MenuHomeDevCentral

Free correctly the memory for variables passed to the TCL interpreter
Open, HighPublic

Description

@xcombelle noticed malloc calls wasn't followed by free in the library source code.

At writing time, this probably occured:

  • static strings was passed to the TCL interpreter
  • they was rightly declared as static
  • compiler complained a const string doesn't match Tcl_Setresult char* signature
  • code switched to char*
  • code doesn't make anymore any warranty of immutability, but advertise so to TCL
https://www.tcl.tk/man/tcl/TclLib/Interp.htm says (seems to be for TCL_STATIC):

Normally, results are assumed to be statically allocated, which means that the contents will not change before the next time Tcl_Eval is called or some other command procedure is invoked. In this case, the freeProc field must be zero."

Tcl_ResetResult clears the result for interp, freeing the memory associated with it if the current result was dynamically allocated. It leaves the result in its normal initialized state with interp->result pointing to a static buffer containing TCL_RESULT_SIZE characters, of which the first character is zero. Tcl_ResetResult also clears the error state managed by Tcl_AddErrorInfo and Tcl_SetErrorCode.
Tcl_FreeResult is a macro that performs part of the work of Tcl_ResetResult. It frees up the memory associated with interp's result and sets interp->freeProc to zero, but it doesn't change interp->result or clear error state. Tcl_FreeResult is most commonly used when a procedure is about to replace one result value with another.

This comp.lang.tcl post by Adrian Ho explains very well the difference between TCL_STATIC and TCL_DYNAMIC in term of promises done by the library code to the TCL interpreter.

It seems if we only want to free the pointer, the macro TCL_DYNAMIC could be use. If we need more complex behavior, a callback should be provided.

Relevant files repository:

rRABBITMQTCL

Event Timeline

[ High priority as that's have a slight but very annoying for stability impact on code using the library as a long term runtime lifecycle. This doesn't really affect scripts connecting once, getting message, disconencting. ]

According to this answer on stack overflow http://stackoverflow.com/a/867996/128629

the correct use of a constant string to pass it as a char* in C without compiler warning is to affect it to a char [] variable

so something like:

char MY_CONSTANT_STRING[]="my constant string";
function_expecting_char_star( MY_CONSTANT_STRING);

by the way how one can see the source where this task refer ?

If I understand well, to require Tcl to do the copy, and so be free to allocate where we want the string (also in the stack), we should pass it as TCL_VOLATILE. TCL_DYNAMIC is intended to create a modifiable variable, but the allocation should saty

[ This task isn't in my immediate radar. ]