Then I checked the code of cppcheck situationally, and he introduced me to thoughtfulness ..

An example of that code, sawed too much:

 void * t(void * p, size_t osz) { if (!(p = realloc(p, ((osz + 1) * sizeof(int))))) { return NULL; } return *p; } 

what he actually advises:

(error) Common realloc mistake: 'p' nulled but not freed upon failure

so the question is how to remove if returned NULL ?! or copy the address of the variable to another in advance, and in case of failure, delete the link to the original? .. but for some reason it seems to me that there will also be NULL ..

to check in practice there seems to be no possibility, realloc does not seem to break ..

your opinion?

    1 answer 1

    or copy the variable's address to another in advance, and in case of failure, delete the link to the original

    Exactly. So it should be. Only as for me - it is better to assign the result of realloc another variable - so it is more logical, like

     void * newPtr = realloc(p,.... if (newPtr == NULL) { ... обработка проблем; p содержит указатель на старый блок } else { p = newPtr; } 

    but for some reason it seems to me that there will also be NULL

    Well if you do

     int x = 5; int *i = &x; int *j = i; i = NULL; 

    are you not afraid that j will also be NULL ? :)

    One last thing: how do you manage to return a dereferenced pointer to void as void* ? :)

    • Thank you, this is a strongly neutered version :) with void s :) and in the example with i , j these are not pointers on each other .. :) and NULL will probably comprehend realloc itself inside the parameter passed to it .. of course I am unsure of this, and certainly depends on the implementation. - NewView
    • In C, the transfer of parameters to a function is performed only by value (when they talk about a separate transfer to an address, it is simply the transfer of an address by value :)) so it cannot change the transmitted variable realloc . Read again about passing arguments to functions. And in the example, from what you replace with pointers ... In general, I correct in the response to pointers - see for yourself. - Harry
    • Yes, yes, with zero (NULL) I agree of course :) and so i = ((int*)&0); ? - NewView
    • And how do you plan to find the address of zero? :) But even so - in my example, NO CHANGE IN THE VALUE i WILL NOT AFFECT THE CHANGE IN THE VALUE j - Harry
    • Completely agree :) - NewView