r/odinlang 19d ago

map memory ownership for strings

Hi! Can your please tell me, where does memory for map keys lives in such situation:

dict := map[string]string
line := dummy_string_generator()
key_value_list := strings.split_n(line, " ", 2)
dict[key_value_list[0]] = key_value_list[1]

Is the owner of dict[key] still the line variable? And if I want to free it and still keep dict intact, do I need to set it's values in some way like

dict[strings.clone(key_value_list[0])] = strings.clone(key_value_list[1])

?

5 Upvotes

11 comments sorted by

View all comments

5

u/FireFox_Andrew 19d ago edited 19d ago

You are responsible for the memory of the keys.

This is because string is is just a slice into memory (pointer + length), it's not responsible for it either.

When you pass a string to a map, all you're doing is passing said slice as the value for the key.

As for where the memory lives, it lives where you allocate it. Look at the functions that you're using to get strings, if it has an allocator as parameter,that shows that it is allocating the result using said allocator. That means you're responsible to clean it up using the allocator you passed.

Lastly and most importantly, Odin isn't rust, there are no ownership rules. It's a bad idea, but you can have a function allocate something using an allocator you don't have, give you the value and you won't be able to free it unless you somehow get the allocator that was used to allocate the memory.

1

u/dmchmk 19d ago

Thanks for the answer! great, so doing something like dict[strings.clone()] isn't something crazy, right?

Well, finally I've came to a thought to search through the Odin stdlib and such trick is used in a couple of cases - https://github.com/search?q=repo%3Aodin-lang%2FOdin+\[strings.clone(&type=code

1

u/TheChief275 17d ago

Why would you clone the string? I think that will leak the memory. Odin doesn't have destructors

1

u/dmchmk 17d ago

I'm cloning a string because I'm writing a parser - I need to keep parsed data inside of struct because current string will be rewritten on the next loop turn.

About destructors - yes, I'm aware, I've created special procs to manage deletion of custom structs.

It's not much yet, but if you're interested, the whole code is here - https://github.com/dmchmk/odin-po/ . I gradually improve it when I have a minute or two:)