4

I have a question about my little c program:

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

int main() {
    int c, len;
    int max = 100;
    char *buffer = malloc(max);

    for (len = 0; (c = getchar()) != EOF; len++) {
        buffer[len] = c;
        if (len == max - 1) {
            buffer = realloc(buffer, (len + max));
            if (buffer == NULL) {
                printf("Error: Out of memory!\n");
                return 1;
            }
            max += 100;
        }
    }
    buffer[len] = '\0';

    for (; len >= 0; --len) {
        printf("%c", buffer[len]);
    }                                    

    printf("\n");
    free(buffer);
    return 0;
}

My task is to write a program which inserts a text and gives a backwards output of the text. If there happens to be a problem with the allocated memory an error message should occur. According to my test report from university the first lines of the output are 1 character too long, I can't determine the reason for this problem and I'm seeking for some advice and help

chqrlie
  • 131,814
  • 10
  • 121
  • 189
werther
  • 47
  • 7

1 Answers1

1

First of all, you should understand your problem. You have the following diagnostic:

the first lines of the output are 1 character too long

This is not enough! You should make a specific example. If you give your program some small input, e.g. abc, what will it output? And what should it output? This is less abstract than "1 character too long", and possible to debug.


Your program has an off-by-one bug:

buffer[len] = '\0';
...
   printf("%c", buffer[len]);

The first character it will output will be a null character \0. It may not be visible on screen (it's an "unprintable" character), so to debug this you better make your output more verbose, like this:

   printf("Character '%c', whose code is %d\n", buffer[len], buffer[len]);

Note the following features that make debugging easier:

  • Apostrophes around the printed character will make it clear where your code outputs a space
  • Verbose format will make it clear how many characters your code outputs
  • Printing the character a second time as integer (%d) will output its code and will help you debug unprintable characters

Your program has more than one bug. Use the above ideas to reproduce and isolate bugs one by one. Please also read this.

Community
  • 1
  • 1
anatolyg
  • 26,506
  • 9
  • 60
  • 134