Search code examples
cdynamic-memory-allocation

Memory Management in C - Allocation of memory slots


Dear Stack Overflow Family - Happy Near Year !!! Have all a wonderful time.

I need help to learn memory management in C (and perhaps in general computing). Some book references would be great. All questions below are specific to C Programming.

  1. Are the memory addresses assigned during compilation or execution? I have an impression that even though the addressed are assigned during execution, the sizes and offsets are defined during compilation. Your comments are much appreciated.
  2. Another specific case on above question - say we define a char array. For this data type we just access the array using pointer to the first element. I need to identify for myself - is the pointer the only source required to retrieve the data (all elements of the array) - i.e. when we try to read the array, we just access the first element, and read until we reach the first null character? Or maybe there's a separate register showing the array length so we know where to stop. Again is it defined in compilation or execution?
  3. In Addition to above, I assume we really use a register to record used memory slots - so when we define next data type we need to know which slots are free. Just need some guidance, or maybe some references, books on this.

Thanks in advance, Mehdi

No specific problems - just need advice.


Solution

  • Memories are allocated statically for this code char c[2] = { 'c', 'q'}; But, char* c = malloc(sizeof(char)*2);is allocated dynamically. and here is how you iterate over string literals in C

    char str[] = "example";
    char *ptr = str;
    while(*ptr != '\0') { // *ptr dereferences the pointer
        printf("%c", *ptr); 
        ptr++; 
    }
    

    Memory allocation: The compiler doesn't use a register to track free/used memory slots. Memory management is done at runtime. For dynamic allocation, functions like malloc() and free() are used to request and release memory. Static/local variables' memory is managed automatically - allocated when in scope and freed when out of scope.