Page 130 - Programming Microcontrollers in C
P. 130

Memory Management        115

                          not taken, none of the usual pointer arithmetic will work. If the
                          memory is not available to be allocated, the allocation program will
                          return a NULL.
                              A second dynamic memory allocation function is

                   void* calloc(int number, size_t n);
                          This function returns a pointer to a type void. It takes two arguments.
                          The first argument is the number of items and the second argument is
                          the size of the specific item. Therefore, if you wished to allocate space
                          for ten TNODEs from the above problem, you should use

                    (TNODE *) calloc(10, sizeof(TNODE));
                          calloc() differs from malloc() in that it returns a pointer to
                          initialized space. The calloc() function initializes all memory
                          assigned by the function to zero. When memory is allocated by ei­
                          ther malloc() or calloc(), this memory must be returned to
                          the system. If allocated memory is not returned to the system, even­
                          tually all of the available memory will be allocated. Further attempts
                          to allocate memory will fail. If the return pointer from the allocation
                          function is not tested and properly handled when a NULL is returned,
                          the program will exhibit undefined behavior. This problem can be
                          avoided by deallocating memory when it is no longer needed by the
                          program. The function
                   void free(void* );

                          will release allocated memory. The argument in this case must be a
                          pointer that was returned from an allocate function, either malloc()
                          or calloc().
                                 An additional memory allocation function is

                    void *realloc(void *,size_t);

                          The first parameter here is a pointer to a previously allocated memory
                          block, and the second is the new size that you want for the allocated
                          memory. This function will change the size of the allocated memory
                          block. If you are reducing the size of the block, the pointer returned
                          will probably be the same as that passed to realloc. If you are
                          increasing the size of the block, and there is not enough contiguous
                          memory available, the function will search for a proper sized block.
   125   126   127   128   129   130   131   132   133   134   135