6

For example, in javascript

I can say

var x = 5;

Later I can do

x = 'a';

and then

x = "hello";

So, how is memory allocated for the variables? As it is, all variables have a common type 'var' and values of variables can change at run-time as seen above. Isn't it a difficult task to allocate and manage memory for these variables? Exactly, how is it done?

Real Red.
  • 4,991
  • 8
  • 32
  • 44
  • See also this stack overflow [How variables are allocated memory in Javascript?](http://stackoverflow.com/questions/2800463/how-variables-are-allocated-memory-in-javascript) especially a comment that contains a link to this dissertation [Three Implementation Models for Scheme](http://www.cs.unm.edu/~williams/cs491/three-imp.pdf) by R. Kent Dybvig. – Richard Chambers Jan 17 '14 at 15:59

2 Answers2

3

Python uses a technique called reference counting, which basically puts a counter in the value. Each time a reference to a value is created, the counter is incremented. When a reference to the value is lost (for instance when you assign a new value to 'x'), the value is decremented. When the counter reaches zero, that means that no reference to the value exists, and it can be deallocated. This is a simplified explanation, but that's at least the basics.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • so what will x be treated as? when i say x=5, then will it be treated as an int or a string during allocation? and where will the type information be stored? – Real Red. Feb 24 '09 at 15:50
  • How the variable is allocated and the type information is stored will be implementation specific. If you want to see how one implementation does it, you can download Rhino: JavaScript for Java http://www.mozilla.org/rhino/. – Grant Wagner Feb 24 '09 at 16:06
  • This is only true in CPython and also ignores garbage collection. You should fix it. – Antimony Aug 19 '12 at 18:56
0

Well, those variables are references to immutable strings which are allocated at compile time.

Of course it depends on the VM, but in general, I think, most C-based scripting languages allocate a large block of memory, expanding it as necessary and do their own allocation within that, rarely if ever giving anything back to the O/S. Especially in a lexically scoped language, which almost all of them are, variables are all allocated dynamically within this block, not on anything analogous to a C stack, and they are freed with either reference counting or with a garbage collector.

If your scripting language is running on the JVM, or .NET, or something like it (Parrot?), creating a variable is merely the creation of something like a Java object. Some time after there are no more references to the object, the garbage collector will reclaim the memory.

Joel Hoffman
  • 346
  • 1
  • 3