With way too long

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 that inserts text and gives the inverse text output. If there is a problem with the allocated memory, an error message should appear. According to my test report from the university, the first lines of output have one character for too long, I cannot determine the cause of this problem, and I am looking for advice and help.

+4
source share
1 answer

First of all, you must understand your problem. You have the following diagnostics:

first lines of output are too long 1 character

! . , . abc, ? ? , "1 " .


" ":

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

, , \0. ( "unprintable" ), ,

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

, :

  • ,
  • , .
  • (%d)

. , . .

+1

Source: https://habr.com/ru/post/1662123/


All Articles