Page 103 - C-Language
P. 103

you should always check the return value for easier debugging.


        This is bad:


         char* x = malloc(100000000000UL * sizeof *x);
         /* more code */
         scanf("%s", x); /* This might invoke undefined behaviour and if lucky causes a segmentation
         violation, unless your system has a lot of memory */


        This is good:


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

         int main(void)
         {
             char* x = malloc(100000000000UL * sizeof *x);
             if (x == NULL) {
                 perror("malloc() failed");
                 exit(EXIT_FAILURE);
             }

             if (scanf("%s", x) != 1) {
                 fprintf(stderr, "could not read string\n");
                 free(x);
                 exit(EXIT_FAILURE);
             }

             /* Do stuff with x. */

             /* Clean up. */
             free(x);

             return EXIT_SUCCESS;
         }


        This way you know right away the cause of error, otherwise you might spend hours looking for a
        bug in a completely wrong place.


        Newline character is not consumed in typical scanf() call


        When this program


         #include <stdio.h>
         #include <string.h>

         int main(void) {
             int num = 0;
             char str[128], *lf;

             scanf("%d", &num);
             fgets(str, sizeof(str), stdin);

             if ((lf = strchr(str, '\n')) != NULL) *lf = '\0';
             printf("%d \"%s\"\n", num, str);
             return 0;



        https://riptutorial.com/                                                                               79
   98   99   100   101   102   103   104   105   106   107   108