Stack & Heap
How data is allocated on the stack and heap.
C++
Rust
Java
{
// single char allocated on the stack
char a = 'a';
// single char allocated on the heap
// char pointer allocated on the stack
char *b = new char('b');
// array of 23 chars allocated on the heap
// char pointer allocated on the stack
char *c = new char[23];
// heap allocated char is freed
delete b;
// heap allocated array is freed
delete[] c;
}
{
// single char allocated on the stack
let a: char = 'a';
// single char allocated on the heap
//
let b = Box::new('b');
// array of 23 chars allocated on the heap
// char pointer allocated on the stack
let c = Box::new(['c'; 23]);
// heap allocated memory is freed when the
// variable goes out of scope
// however, you can force freeing by using
// the mem::drop method
mem::drop(b);
mem::drop(c);
}
{
// single char allocated on the stack
char a = 'a';
// Character object allocated on the heap
// Character reference allocated on the stack
Character b = new Character('b');
// array of 23 chars allocated on the heap
// char reference allocated on the stack
char[] c = new char[23];
// no way to explicitly free memory in Java
// best we can do is set to null and wait for
// the garbage collector
b = null;
c = null;
}
In C++ data is allocated on the stack unless the keyword new
is used, then it is allocated on the heap. As
seen in the examples you much call the appropriate version of new
depending upon if an object or array is
being allocated. Memory is freed from the stack when the variable goes out of scope. Heap allocated memory is freed when
the delete
keyword is called.
In Rust to allocate memory on the heap, the Box<T>
struct is used. When the variable assigned to a
new Box
goes out of scope, the memory in the box is freed.
Java is very similar to C++ except that memory is freed via garbage collection instead of an explicit call to delete
.
Also, with Java there is only one version of new
for both arrays and objects, but primitives cannot be allocated
on the heap.