Realloc behavior when the new size is the same as the old

I am trying to make the 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 allocated dynamically. I would like to reduce realloc calls to make the code more efficient. I would like to know how realloc will behave if the new size is equal to the old. Will the call be simply ignored?

+6
source share
3 answers

It is not specified in standard C. All guaranteed standards are C: the contents of the new object must be the same as the old object until it was released, up to the smaller size of the new and old size.

However, if you use GNU libc, it explicitly talks about returning the same address, see here for details.

If the new size you specify matches the old size, realloc guaranteed not to change anything or return the same address that you specified.

+8
source

I will not rely on the fact that realloc will behave as a no-op if the size does not change (although this seems reasonable to him), but then you do not need to: if the iCount value has not changed, do not make a call to realloc.

+3
source

The C standard does not specify what will happen, so you are at the mercy of the implementation. I can’t imagine a semi-like implementation that will not return the passed pointer, but a safe option is to check if the distribution size has changed in your own code. It will also miss the function call.

(BTW, please do not add the return value from realloc . This is not necessary, and it may hide undefined behavior if you forget #include <stdlib.h> .)

+2
source

Source: https://habr.com/ru/post/953168/


All Articles