limido
limido

Reputation: 327

what is wrong with this realloc use

I'm trying to get unlimited input from user, using realloc. this is what i've done so far:

int getCharactersFromUser(char* arr,char terminator)
{
char c = getch();
int length =0;
while(c!=terminator)
    {
    arr = realloc(arr, sizeof (arr)*(++length));
    arr[length-1]=c;
    c = getch();
    }
return length;
}

i call this method with an arr like this: char *unknownArr = calloc(0,sizeof *unknownArr); int length = getCharactersFromUser(&unknownArr,TEMINATOR_FOR_LIST); here TEMINATOR_FOR_LIST is eof

Upvotes: 0

Views: 149

Answers (1)

simonc
simonc

Reputation: 42195

If you want to change the caller's copy of arr, you need to pass a pointer to a pointer.

Also, sizeof (arr) gives you the size of char*; your code appears to be assuming sizeof(char). This is guaranteed to be 1, allowing your memory size calculation to be simplified.

int getCharactersFromUser(char** arr,char terminator)
{
    *arr = NULL; // first call to realloc will crash if `*arr` is uninitialised in caller
    char c = getch();
    int length =0;
    while(c!=terminator)
    {
        *arr = realloc(*arr, ++length);
        (*arr)[length-1]=c;
        c = getch();
    }
    return length;
}

Upvotes: 7

Related Questions