0

why can we use the stack for all our needs?

NOTE: it will be very good if you give an example while explaining because it is easier to understand with examples.

sorry for bad English.

trincot
  • 317,000
  • 35
  • 244
  • 286
Stel Team
  • 77
  • 9

1 Answers1

7

In practice the call stack is limited and small. The typical limit is a few megabytes. In contrast, you could often allocate gigabytes in heap memory.

(on some systems, you might configure the system to have a larger stack; but you need to tell your users if you need that)

Also, and most importantly, the call stack is a stack, so has a LIFO (last in first out) discipline. In many cases, you want to release objects in an order unrelated to their allocation or just in a "first allocated, first destroyed" order (and that is impossible on a stack).

Consider reading something about garbage collection, e.g. the GC handbook. It teaches you useful concepts and terminology about dynamic memory allocation (even for C programs with manual memory management). Read also about the virtual address space of your process (se also this answer, at least for Linux).

Another advantage of dynamic memory allocation is that the same executable can run on various computers (with various resources, in particular different amount of RAM), but won't be able to process the same amount of data. If you had to allocate all the memory statically, this would not be the case (e.g. a C program with 50 gigabytes of static data could not even start on my laptop).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • @StelTeam: Reminder: parameters may also be placed on the stack when calling a function. – Thomas Matthews Feb 23 '18 at 17:37
  • It depends upon the ABI. On my Linux/x86-64 system, up to six parameters go thru registers, not on the stack – Basile Starynkevitch Feb 23 '18 at 17:38
  • In practice, the stack is exactly as big as the space that is allocated for it. The _default_ may be small (relative to the needs of some application), but there almost always is some way to explicitly reserve space for a stack. – Solomon Slow Feb 23 '18 at 17:38
  • 1
    The _real_ reason is the LIFO thing. It's kind of hard to write a function that adds a new node to a linked data structure, if the lifetime of the new node can not exceed the duration of the function call in which it was created. – Solomon Slow Feb 23 '18 at 17:41