Page 89 - C-Language
P. 89

char *dest = malloc(strlen(src) + 1); /* RIGHT */

         strcpy(dest, src);


        This is because strlen does not include the trailing \0 in the length. If you take the WRONG (as shown
        above) approach, upon calling strcpy, your program would invoke undefined behaviour.

        It also applies to situations when you are reading a string of known maximum length from stdin or
        some other source. For example


         #define MAX_INPUT_LEN 42

         char buffer[MAX_INPUT_LEN]; /* WRONG */
         char buffer[MAX_INPUT_LEN + 1]; /* RIGHT */

         scanf("%42s", buffer);  /* Ensure that the buffer is not overflowed */



        Forgetting to free memory (memory leaks)


        A programming best practice is to free any memory that has been allocated directly by your own
        code, or implicitly by calling an internal or external function, such as a library API like strdup().
        Failing to free memory can introduce a memory leak, which could accumulate into a substantial
        amount of wasted memory that is unavailable to your program (or the system), possibly leading to
        crashes or undefined behavior. Problems are more likely to occur if the leak is incurred repeatedly
        in a loop or recursive function. The risk of program failure increases the longer a leaking program
        runs. Sometimes problems appear instantly; other times problems won't be seen for hours or even
        years of constant operation. Memory exhaustion failures can be catastrophic, depending on the
        circumstances.

        The following infinite loop is an example of a leak that will eventually exhaust available memory
        leak by calling getline(), a function that implicitly allocates new memory, without freeing that
        memory.


         #include <stdlib.h>
         #include <stdio.h>

         int main(void)
         {
             char *line = NULL;
             size_t size = 0;

             /* The loop below leaks memory as fast as it can */

             for(;;) {
                 getline(&line, &size, stdin); /* New memory implicitly allocated */

                 /* <do whatever> */

                 line = NULL;
             }

             return 0;
         }



        https://riptutorial.com/                                                                               65
   84   85   86   87   88   89   90   91   92   93   94