Virtual machine design with separate stack and heap

485 views Asked by At

I'm trying to learn a bit more about virtual machines and programming languages in general by implementing some of the stuff that is found in books. The book I'm currently going through keeps the stack and the heap in one memory area. The stack grows upwards and the heap grows downwards. I'd like to know what the benefits of this are other than maybe a simpler strategy for load/store operations because you don't need to distinguish between two different memory areas.

The reason I ask is because I'm thinking of deviating from the plan in the book and having two different memory areas for the stack and the heap. That seems to make more sense to me and I don't have to worry about the stack and heap registers running into each other.

2

There are 2 answers

0
miraculixx On BEST ANSWER

I'd like to know what the benefits of this are other than maybe a simpler strategy for load/store operations (...)

The benefit is that you don't need virtual memory, which makes this concept work on the simplest of CPUs/architectures. Also you don't need an operating system that keeps track of memory areas and their assignment to programs. In other words, such an implementation is well suited for e.g. small-scale embedded systems that typically don't have (and don't need) the processing power of a modern day desktop or server CPU.

(...) because you don't need to distinguish between two different memory areas.

I suppose by memory areas you mean the concept of multiple contigous memory spaces which are separated such that they each have an address range of relative indexes (0, ..., n) where n is the maximum number of bytes in that area.

That makes a lot of sense if you have virtual memory, that is the CPU implements a layer on top of the physical memory that gives programs the illusion of each having a seperate, contigous memory space.

0
Will Hartung On

Well, on older machines of limited memory and no virtual memory, the two sections of memory represented the two opposite ends of the free space of the machine. If you have 48k of contiguous space, one end is the stack growing upward, and the other is the heap growing downward. Eventually they collide and you are "out of memory".

So that's where the inspiration comes from. Modern machines are certainly not memory challenged (necessarily) and you have the VM system to help isolate disparate parts like the heap and stack. Then you have no real reason to "grow up" on one and "grow down" on the other. Rather you allocate them to the desired size, and just start growing up until you run out.

Also, of course, today, with the VMs you can control execution and such on the stack are (or even the heap area). Wasn't really an issue on the smaller, older machines in the past.