Page 91 - C-Language
P. 91

setting a pointer to NULL, there is no risk of double-freeing memory if the pointer is passed to
        free(). Keep in mind that double-freeing memory can lead to very time consuming, confusing, and
        difficult to diagnose failures.


        Copying too much



         char buf[8]; /* tiny buffer, easy to overflow */

         printf("What is your name?\n");
         scanf("%s", buf); /* WRONG */
         scanf("%7s", buf); /* RIGHT */


        If the user enters a string longer than 7 characters (- 1 for the null terminator), memory behind the
        buffer buf will be overwritten. This results in undefined behavior. Malicious hackers often exploit
        this in order to overwrite the return address, and change it to the address of the hacker's malicious
        code.

        Forgetting to copy the return value of realloc into a temporary



        If realloc fails, it returns NULL. If you assign the value of the original buffer to realloc's return value,
        and if it returns NULL, then the original buffer (the old pointer) is lost, resulting in a memory leak.
        The solution is to copy into a temporary pointer, and if that temporary is not NULL, then copy into
        the real buffer.



         char *buf, *tmp;

         buf = malloc(...);
         ...

         /* WRONG */
         if ((buf = realloc(buf, 16)) == NULL)
             perror("realloc");

         /* RIGHT */
         if ((tmp = realloc(buf, 16)) != NULL)
             buf = tmp;
         else
             perror("realloc");


        Comparing floating point numbers


        Floating point types (float, double and long double) cannot precisely represent some numbers
        because they have finite precision and represent the values in a binary format. Just like we have
        repeating decimals in base 10 for fractions such as 1/3, there are fractions that cannot be
        represented finitely in binary too (such as 1/3, but also, more importantly, 1/10). Do not directly
        compare floating point values; use a delta instead.


         #include <float.h> // for DBL_EPSILON and FLT_EPSILON
         #include <math.h>  // for fabs()

         int main(void)



        https://riptutorial.com/                                                                               67
   86   87   88   89   90   91   92   93   94   95   96