Reading and analyzing rooms from text file

The readLine function does look a bit error prone:

char * readLine(FILE * fin){
    char buffer[BMAX];
    int i,j;
    char ch;
    char * l;
    i = 0;
    ch = getc(fin);
    if (ch == EOF)
        return NULL;
    while (ch!='\n' && i < (BMAX - 1)){
        buffer[i] = ch;
        i++;
        ch = getc(fin);
    }
    // The test on the next line is not necessary: it will be caught
    // by the first run of the following while loop.
    if (ch != '\n')
        while (ch != '\n')
            ch = getc(fin);
    buffer[i] = '\0';
    // Allocate a region of memory of (probably) i+1 bytes
    l = malloc((i+1) * sizeof(char));
    // j will range from zero to i, terminating when j = i+1
    for (j = 0; j <= i; j++)
        l[j] = buffer[j];
    // j now equals i+1 and l[j] is one beyond the size of the memory allocated at l.
    l[j] = '\0';

    return l;

}

Fix this by changing the condition on the loop

    // j will range from zero to i-1, terminating when j = i
    for (j = 0; j < i; j++)
        l[j] = buffer[j];
    // j now equals i and l[j] is the last element of the memory allocated at l.
    l[j] = '\0';

Notes:

1) You should always check the return value from malloc.

2) The actual size of memory allocated by malloc may be more than that requested, depending on the heap implementation, the processor architecture and the actual library function used.

Also, you should be nice and call free on every pointer that you have assigned using malloc. The memory will be cleaned up eventually when the process terminates (if it’s running in a fairly common OS), but it’s good practice to do housekeeping, especially on those temporary buffers returned by readLine.

You may also want to take a look at the if(rp > MAX) line in readRooms and see if could cause an over run for the 11th room.

Leave a Comment