Thursday 3 September 2020

Unit 1 . Static and dynamic memory..

 

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with staticdefined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

  1. void func() { 
  2. int i; /* `i` only exists during `func` */ 

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

  1. int* func() { 
  2. int* mem = malloc(1024); 
  3. return mem; 
  4.  
  5. int* mem = func(); /* still accessible */ 

1 comment: