Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

memory - 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( '
' );
        break;
    default:
        printf("%s", s);
        break;
}
printf("
");
    }

    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!='
' && c !='') 
{
    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] = '';
reverse(buffer);

return 0;

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...