Mano Mini
Mano Mini

Reputation: 613

How does Bash manage its memory?

For example, if I declare a variable a=8:

Upvotes: 9

Views: 2366

Answers (2)

chepner
chepner

Reputation: 531205

Memory management isn't something you need to concern yourself with in any shell language. Suffice it to say, bash is responsible for the allocation and deallocation of any memory used.

All interpreted languages store their variables on the heap; even if they use a stack, that is dynamically allocated on the interpreter's heap as well.

Upvotes: 2

Soren
Soren

Reputation: 14688

Bash variables like

a=8

are stored as heap memory, and they are never removed unless the user explicitly unset the variable -- so in essence the user is responsible for deleting it if it ever needs deleting.

In bash 2.05 variables are internally managed through a hash table, where memory for the hash table is obtained and release by "malloc" and "free". The removing of the elements from the hash table does not immediately remove the element from the hash table, but it is cleaned up through a garbage collection flush_hash_table that is called at key points in the execution.

Bash version 4.4 have a re-written some of the hash tables, and the flush_hash_table no longer exist, but is replaced with a functionhash_flush.

Hence different versions and port could behave differently and you should not rely on that the memory is actually immediately released even if you do an unset, or expect any particular behavior of memory when writing shell scripts

Upvotes: 9

Related Questions