Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPython - Internally, what is stored on the stack and heap?

In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc.

I was wondering, does CPython do the same thing internally? What does it store on the stack, and what does it put on the heap?

like image 928
Justin Ethier Avatar asked Mar 01 '10 02:03

Justin Ethier


People also ask

What is stored in stack and heap?

The Heap Space contains all objects are created, but Stack contains any reference to those objects. Objects stored in the Heap can be accessed throughout the application. Primitive local variables are only accessed the Stack Memory blocks that contain their methods.

What type of data is stored in stack and heap?

Stack memory stores primitive types and the addresses of objects. The object values are stored in heap memory. An object reference on the stack is only an address that refers to the place in heap memory where that object is kept.

What things are stored on the heap?

The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space. It supports Dynamic memory allocation. The heap is not managed automatically for you and is not as tightly managed by the CPU.

Does Python store everything on the heap?

All objects and instance variables are stored in the heap memory. When a variable is created in Python, it is stored in a private heap which will then allow for allocation and deallocation.


2 Answers

All Python objects in the CPython implementation go on the heap. You can read in detail how Python's memory management works here in the documentation:

Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.

Note that Python itself is just a language, and says nothing about how internals like memory management should work; this is a detail left to implementers.

like image 60
John Feminella Avatar answered Oct 30 '22 13:10

John Feminella


Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack (as operands and results of its bytecode operations) are always references (to values that live elsewhere).

like image 23
Alex Martelli Avatar answered Oct 30 '22 15:10

Alex Martelli