Search code examples
cdynamic-memory-allocationc89

realloc() invalid pointer error when increasing size of string in a function


When i run code it show realloc() invalid pointer error.

Is anything wrong in input() function?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
char *input(void)
{
    int n = 1;
    char *str = malloc(sizeof(char));
    *str = '\0';
    while((*str=getchar())!='\n')
    {
        n++;
        str = realloc(str,sizeof(char)*n);
        str++;
    }
    return str;
}

int main(int argc, char const *argv[])
{
    char *str = input();
    printf("%s",str);
    free(str);
    return 0;
}

Solution

  • You make a few errors:

    • you return the end of the string, not the beginning.

    • realloc needs the original address (see Thomas' answer)

    • realloc may return a new address

    • you do not terminate the string.

    The following fixes these errors and includes some suggestions:

    char *input(void)
    {
        size_t i=0;
        int c;
        char *str = malloc(1);
        if (!str) return 0;
        while((c=getchar())!=EOF && c!='\n')
        {
            str[i]= c;
            if ((newstr = realloc(str,i+1))==0)
                break;          // out of memory: return what we have
            str= newstr;
            i++;
        }
        str[i]= '\0';
        return str;
    }