previous | start | next

strcpy, gets, sprintf

Many standard library i/o functions write data into a string and make programs that use them susceptible to buffer overflow attacks:

        const int N = 5;
        char b[N];

        /**
        * 1. Not enough room in b for "Hello, World!"
        */

        strcpy(b, "Hello, World!");

        /**
        * 2. Reads an input line and stores it in b (discarding the
        *    newline, but adding a null byte). Not enough room
        *    in b for input lines longer than 4 characters.
        */

        gets(b);

        /**
        * 3. Converts time in ticks since Januarty 1, 1970 (or the
        *    'epoch' starting date) to a string representation of
        *    the current date and time and stores it in b. E.g.,
        *    "Thu May 14 09:29:24 2009" copied to b.
        *       */
        time_t ticks = time(0);  // current time in ticks since epoch
        sprintf(b, "%.24s", ctime(&ticks));

     


previous | start | next