Using Realloc in C

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 12:23:05

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.

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.

Yes, realloc could be used to slightly simplify your code. If you're not interested in error-handling, then this:

char *tmp = malloc(size*2);
memcpy(temp, buffer, size);
free(buffer);
buffer = tmp;

is essentially equivalent to this:

buffer = realloc(buffer, size*2);

If you are interested in error-handling (and you probably should be), then you will need to check for NULL return values. This is true of your original code too.

Yes, to simplify your code, you can replace

if ( i >= buffer_size )
{
    temp = (char*)malloc(buffer_size*2);
    memcpy( temp, buffer, buffer_size );
    free( buffer );
    buffer_size *= 2;
    buffer = temp;
}

with

if ( i >= buffer_size )
    buffer = realloc(buffer, buffer_size *= 2);

This does not take into account error checking, so you will need to check to make sure realloc doesn't return NULL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!