visitor
visitor

Reputation: 111

Can you read in a variable length string from standard input using getchar()

I was just experimenting and wondered why my attempt did not work (the program crashes).

#include <stdio.h>
#include <stdlib.h>  
int main(int argc, char **argv)
{
    
    char *list;
    list =  (char*)malloc(sizeof(char));
    char a;
    int i = 0;
    
    while ( (a =getchar()) !='\n'){
        
        list[i]= a;
        list = (char*)realloc(list,sizeof(char));
        ++i;
       
    } 
    
    printf("%s",list);
    free(list);
    
    
    return 0;
}

Upvotes: 0

Views: 278

Answers (1)

Jessica Pennell
Jessica Pennell

Reputation: 578

sizeof(char) is always 1. You need to multiply this by the length of your list.

To keep track of the size of your list it's best to use a size_t or an integer, e.g.

list = (char*)realloc(list,sizeof(char)*(i+2));

As @Ian Abbot mentions in the comments, we add 2 instead of 1 to make room for the null terminator (below).

Note : I am retaining your code style but please see the advice in the comments to your original question, this cast is not needed.

After your loop you also need a null terminator.

...

    }
    list[i] = 0;

Upvotes: 1

Related Questions