Can realloc crash (return NULL) when trimming?

If you do the following:

int* array = malloc(10 * sizeof(int));

and I use realloc:

array = realloc(array, 5 * sizeof(int));

In the second line (and only she), can she return NULL?

+6
source share
7 answers

Yes it can. For realloc()there are no guarantees of implementation, and it can return another pointer, even with a reduction.

For example, if a particular implementation uses different pools for objects of different sizes, it realloc()can actually allocate a new block in the pool for smaller objects and free a block in the pool for larger objects. Thus, if the pool for smaller objects is full, it will fail and return NULL.


Or he may just decide it is better to move the block

, glibc:

#include <stdlib.h>                                                          
#include <stdio.h>                                                           

int main()                                                                   
{                                                                            
    int n;                                                                   

    for (n = 0; n <= 10; ++n)                                                
    {                                                                        
        void* array = malloc(n * sizeof(int));                               
        size_t* a2 = (size_t*) array;                                        

        printf("%d -> %zu\n", n, a2[-1]);                                    
    }                                                                        
}

n <= 6 32 , 7-10 - 48.

, int[10] int[5], 48 32, 16 . ( ) 32 , 16 .

, 48 , - . , , ;).


C99 (7.20.3.4 realloc):

4 realloc ( , ), , .

"" . - , , , .


, , , realloc() . C++, (new/delete allocators) . . .

+11

, , realloc "",

void *safe_trim(void *p, size_t n) {
    void *p2 = realloc(p, n);
    return p2 ? p2 : p;
}

n.

, realloc , "", , , realloc , , realloc.

+5

( ) , , "" realloc .

realloc "" : malloc , free, . , .

+3

. ; " , ".

​​, - .

+3

, .

, . , , .

, bucket-heap ( , tcmalloc).

+2

realloc , NULL. NULL .

, realloc -, , . NULL. .

, NULL .

0

, , realloc() : TCMalloc. ( , )

tcmalloc.cc, do_realloc_with_callback() , , (50% , ), TCMalloc (, , ) .

I am not copying the source code because I am not sure that the copyrights (TCMalloc and Stackoverflow) will allow this, but here is the link to the source (revised as of May 17, 2019).

0
source

All Articles