Segfault after realloc twice

Asked by At

I was trying to write a function which takes an input without length given. ıt works when I try to get a single input,but if I want to get multiple inputs, I get segfault. Below is the code:

char* getinput()
    {
    char c,*str=0,*tmp=0;
    int i=0;

    while(c)
    {
            c=getchar();

            if(c!=EOF && c!='\n')
        {
            if(!(tmp=realloc(str,(i+1)*sizeof(char))))
            {
            free(str);
            return NULL;
            }

        str=tmp;
        str[i++]=c;
        }
        else c=0;
    }

    str[i]=0;
    return str;
}

When I try to get a single input, I can print the string:

string1      
string1

When I try to get multiple inputs, I can't:

string1
Segmentation fault (core dumped)

There is another variable string2. I appreciate any help. Thank you.

1 Answers

1
Jean-François Fabre On

let's say that you input one character

You'll allocate a buffer of one byte, write the character into it then increase the index and do:

str[i]=0;

at this point i==1 and you're writing outside str allocated bounds : undefined behaviour

I suggest you increase your buffer size by one:

if(!(tmp=realloc(str,(i+2)))

(and drop sizeof(char) bit since it's guaranteed to be 1)

A more efficient technique would be to realloc "from time to time", keeping track of the capacity of the allocated buffer, as most vector allocators do, instead of each time.