Bug Buster 002: Can You Bust the Bug?

Bug Buster

Sponsored by Rogue Wave, maker of Klocwork

How good are you at finding errors in code? This is our second bug for you to track down and eradicate. The following is a code snippet compiles fine. Unfortunately, it contains an error. Take a look at the code listing and see if you can find the problem. To make it easier, we’ve listed five options. One of those options is correct while the other four are not.

Can you find the error without looking at the choices?

Bug Buster #2

Here is the Bug Buster:

The code:

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

/* Print "words" made of random letters */

int main()
    int len = 10;    /* length of each string */
    int amount = 5;  /* number of strings */
    int x, y;        /* simple counters */
    char * buffer;   /* buffer to store random string */

    /* create the random strings */
    for(x = 0; x < amount; x++)
        /* allocate memory for string */
        buffer = (char*)malloc(len + 1);
        if (buffer == NULL) exit(1);

        /* build the random string */
        for (y = 0; y < len; y++)
            buffer[y] = rand() % 26 + 'a';
        buffer[len] = '\0';

        /* print the random string*/
        printf("Random string: %s\n", buffer);

    return 0;

Your choices:

You can’t legally compare buffer to NULL without throwing an exception.
The buffer will never be allocated, so the program will always exist.
There is a buffer overflow for the buffer array.
The program has a memory leak.
Nothing is wrong. The code works fine.

How quickly can you find the issue? Feel free to comment on how quickly you found the issue! We will be posting additional snippets over the coming weeks with additional bugs for you to bust. You can click to the next page to find the solution.

More by Author

Must Read