Search code examples
cmemory-leaksdynamic-memory-allocationrealloc

Visual studio warning C6308 exist in shrinking dynamic array


Why I am getting a warning when shrinking arrays?
There is no any way of losing the pointer value.

Warning C6308 'realloc' might return null pointer: assigning null pointer to 'arr_all_guests', which is passed as an argument to 'realloc', will cause the original memory block to be leaked.

arr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));


Solution

  • It means that as it is written the function realloc can return a null pointer. In this case an access to all the early allocated memory will be lost

    arr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*)); 
    

    because the original pointer arr_all_guests will be reassigned with a null pointer.

    You need to use a temporary pointer as for example

    char **tmp = realloc(arr_all_guests, ( *guest_counter - 1 ) * sizeof(char*)); 
    if ( tmp != NULL ) 
    {
        arr_all_guests = tmp;
        --*guest_counter;
    }