Search code examples
cmemoryrealloc

Behavior of realloc when the new size is the same as the old one


I'm trying to make a code more efficient. I have something like this:

    typedef struct{
    ...
    }MAP;



    MAP* pPtr=NULL;
    MAP* pTemp=NULL;
    int iCount=0;
    while (!boolean){
    pTemp=(MAP*)realloc(pPtr,(iCount+1)*sizeof(MAP));
    if (pTemp==NULL){
    ...
    }
    pPtr=pTemp;
    ...
    iCount++;
    }

The memory is being allocated dynamically. I would like to reduce the realloc calls to make the code more efficient. I would like to know how realloc would behave if the new size is equal to the old one. Will the call be simply ignored?


Solution

  • It's not specified in standard C. All standard C guaranteed is: the contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes.

    However, if you are using GNU libc, it says explicitely to return the same address, see here for detail.

    If the new size you specify is the same as the old size, realloc is guaranteed to change nothing and return the same address that you gave.