Home > front end >  Reading arbitrary length strings in C
Reading arbitrary length strings in C

Time:08-05

I've attempted to write a C program to read a string and display it back to the user. I've tested it with a lot of input and it seems to work properly. The thing is that I'm not sure whether or not the c != EOF condition is necessary inside the while expression, and since by definition, the size of a char is 1 byte, maybe I can remove the sizeof(char) expressions inside the malloc and realloc statements, but I'm not sure about this.

Here's the program, also, I manually added a null terminating character to the string:

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

int main(void)
{
    char *str = malloc(sizeof(char));

    if (!str)
        return 1;

    char c;
    char *reallocStr;
    size_t len = 0;
    size_t buf = 1;

    printf("Enter some text: ");

    while ((c = getchar()) != '\n' && c != EOF) {
        if (len == buf) {
            buf *= 2;

            reallocStr = realloc(str, buf * sizeof(char));

            if (!reallocStr)
                return 1;

            str = reallocStr;
        }

        str[len  ] = c;
    }

    str[len] = '\0';

    printf("You entered: %s\n", str);

    free(str);
    
    return 0;
}

CodePudding user response:

As mentioned in the comments, you have a buffer overflow in your code, so you would need to fix that at the very least. To answer your specific questions, sizeof(char) is guaranteed to be 1 (dictated by the c99 spec), so you don't need to multiply by sizeof(char). It's good practice to check for EOF as if your input is coming from an alternate source that has no newline, you don't die (so if someone for example did echo hello | yourprogram from a bash prompt, you wouldn't die).

  • Related