When we write a program, we build and compile it, then the program runs on the PC, which is called the run time.
we say allocate memory at RUN time, This confused me a lot, What's meaning of allocate memory at Run time
Printable View
When we write a program, we build and compile it, then the program runs on the PC, which is called the run time.
we say allocate memory at RUN time, This confused me a lot, What's meaning of allocate memory at Run time
dynamic allocation
See malloc and related functions.
Tim S.
Do you know what it means to allocate memory at compile/build time?
Tim S.
It means that when your user opens your program the memory is not allocated yet.
Another way of looking at it is a work project and getting funding for it (where the money represents memory in this analogy).
At the start of a project I may be able say, "it will cost $1200", and that is great: I ask for that amount, get it approved, less paperwork, ect...
However, there are certain things that I don't know how much it will cost (such as the cost to maintain a machine). To get around this I ask for the funds as I need it. This can be viewed as "dynamically allocated funds". This requires more paperwork, but it is more practical because we don't honestly know how much it will cost and we don't want to allocate all the funds to this one project when there are other projects going on at the same time.
Dynamic memory is allocated on the heap with the malloc() family of functions. In contrast, function calls push their local variables to the stack. Heap memory persists until you free it. You would allocate memory dynamically at runtime when you need to store more data than you initially anticipated.
To illustrate the difference:
Compile time allocation:
static char fred[128];
Run time equivalent:
char * fred;
fred = malloc(128);