Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Realloc in C

Its really a post for some advice in terms of the use of realloc, more specifically, if I could make use of it to simplify my existing code. Essentially, what the below does, it dynamically allocate some memory, if i goes over 256, then the array needs to be increased in size, so I malloc a temp array, with 2x the size, memcpy etc. ( see below ).

I was just wondering if realloc could be used in the below code, to simplify it, any advice, sample code, or even hints on how to implement it is much appreciated!

Cheers.

void reverse(char *s) {
char p;

switch(toupper(s[0])) 
{
    case 'A': case 'E': case 'I': case 'O': case 'U':
        p = s[strlen(s)-1];
        while( p >= s )
            putchar( p-- );
        putchar( '\n' );
        break;
    default:
        printf("%s", s);
        break;
}
printf("\n");
    }

    int main(void) {
char c;
int buffer_size = 256;
char *buffer, *temp;
int i=0;

buffer = (char*)malloc(buffer_size);
while (c=getchar(), c!=' ' && c!='\n' && c !='\t') 
{
    buffer[i++] = c;
    if ( i >= buffer_size )
    {
        temp = (char*)malloc(buffer_size*2);
        memcpy( temp, buffer, buffer_size );
        free( buffer );
        buffer_size *= 2;
        buffer = temp;
    }
}
buffer[i] = '\0';
reverse(buffer);

return 0;

}

like image 576
PnP Avatar asked Nov 29 '11 23:11

PnP


2 Answers

Yes is the short answer. Here's how it would look:

if ( i >= buffer_size )
{
    temp = realloc(buffer, buffer_size*2);
    if (!temp)
        reportError();
    buffer_size *= 2;
    buffer = temp;
}

Note that you still need to use a temporary pointer to hold the result of realloc(); if the allocation fails you still have the original buffer pointer to the still-valid existing buffer.

like image 132
Graham Borland Avatar answered Sep 21 '22 03:09

Graham Borland


Realloc is pretty much exactly what you're looking for - you can replace that entire block inside the if ( i >= buffer_size ) with something like:

buffer = (char*)realloc(buffer, buffer_size*2);
buffer_size *= 2;

Notice that this ignores the error condition (if the return from realloc is NULL); catching this condition is left to the reader.

like image 20
Tim Avatar answered Sep 20 '22 03:09

Tim