Tcl_Alloc

Difference between version 7 and 8 - Previous - Next
Allocate memory using the Tcl library's memory allocation engine. Like `malloc`, but integrates with the [memory] command (if that's defined). Pairs up with [Tcl_Realloc] and [Tcl_Free].

'''`Tcl_Alloc`''' and '''`Tcl_Realloc`''' ''guarantee'' to always return a valid block of memory; they will '''panic''' (call [Tcl_Panic]) if memory allocation fails.  For alternatives that return ''`NULL`'', use '''`Tcl_AttemptAlloc`''' and '''`Tcl_AttemptRealloc`'''.


See also the '''[http://www.tcl.tk/man/tcl/TclLib/Alloc.htm%|%manual]'''.

(Note: the manual does not mention Tcl_Panic)

(2022-10-25 from <aku> in the #tcl chat): [Tcl_Obj] are allocated in thread-local memory pools, and are thus (implicitly) owned by the thread allocating it. Releasing it in a different thread should break things. Because the pool is thread-local access is not mutex protected, there is the expectation that no other thread accesses it, and your [Tcl_DecrRefCount] from the other thread violates this assumption.
In other words: don't Tcl_Alloc/ckalloc something in one thread to release it in another thread. [APN] -> '''THIS IS INCORRECT'''. Tcl_Alloc/ckalloc are thread-safe. In fact posting of events across threads '''requires''' ckalloc to be used (not malloc). The quote above refers to allocated Tcl_Obj instances via Tcl_NewObj, Tcl_NewStringObj etc. In other words do not call Tcl_DecrRefCount (or any other Tcl_Obj related function) on a Tcl_Obj allocated in a different thread. Allocating memory via ckalloc and freeing via Tcl_Free in another thread is perfectly valid.

<<categories>>Tcl C API