How to free a string

I have strings which are dynamically allocated using

sb : strings.Builder
...
mystring := strings.clone_from_bytes( sb.buf[:])
...
// need to free mystring

Now, how do I free the memory used by the string.
(The example above is contrived, but in reality I use the same string builder to build several strings, and then I need to free them later).

1 Like

In this case with clone_from_bytes use delete.
The reason is that the clone function is using make to allocate a slice.

delete(mystring)

But if you did something like this then you have to use free.

mystr := new(string)
free(mystr)
1 Like

…or if you want it to happen at the end of the current context but keep it near the declaration

sb : strings.Builder
mystring := strings.clone_from_bytes( sb.buf[:])
defer delete(mystring)

Last defer in the current context happens first. First defer in the current context happens last. …when the context ends or exits.

1 Like

An alternative for me, would be to use an Arena allocator, so I can dispose of all the strings in a single go.

1 Like

Not bad indeed.

How many bytes is practical for String Buffer nowadays ? I intend to build Arena/Bump Allocator fo my VM/ASM.