title: C Dynamic Memory vs Stack Memory Variables
body: <p>When a C array is created using malloc, the array is stored in the heap, and when a C array is created statically it is stored in the stack. However, what happens if you return an element of a C array initialized statically from a function? My wording may be strange, so here is an example:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  char getStaticElement();
  char getDynamicElement();
  
  int main() {
      char dynamicElement = getDynamicElement();
      char staticElement = getStaticElement();
      printf("Dynamic Element: %c\n", dynamicElement);
      printf("Static Element: %c\n", staticElement);
      return 0;
  
  }
  char getStaticElement() {
      char staticArray [] = {'a','b','c'};
      return staticArray[1]; // returns b
  }
  char getDynamicElement() {
      char * dynamicArray = malloc(sizeof(char)*4);
      dynamicArray [0] ='a';
      dynamicArray [1] ='b';
      dynamicArray [2] ='c';
      dynamicArray [3] ='\0';
      return dynamicArray[1]; // returns b
  }
  </code></pre>
  
  <p>So where is staticElement in memory? Is staticArray cleared off the stack  because the function has finished, or is it still on the Stack because and element of staticArray has been returned? <br>NOTE: I know I did not free dynamic array, and am leaking memory, this is just an example and not meant to be used.</p>