I am wondering what is the right/standard way to use malloc and free. Is it needed to set pointer NULL after free? Basically, which of the two following ways is correct?
double* myPtr = (double*)malloc(sizeof(double)*5);
.....
free(myPtr);
or
double* myPtr = (double*)malloc(sizeof(double)*5);
.....
free(myPtr);
myPtr = NULL;
Or it should be other ways to use malloc and free? Thanks.
Both are fine. The only difference is that the former approach would crash if you tried to free myPtr
a second time.
Depending on the language you're using, the malloc
line could be tidied up a little.
Using sizeof(*myPtr)
is less prone to bugs when you later refactor. If you're using C, the cast is also unnecessary
double* myPtr = malloc(sizeof(*myPtr)*5);
As pointed out by WhozCraig, if you're using C++, there are much easier ways to allocate an array
std::vector<double> ar(5);
gives you an array of 5 double
s that will grow its storage if required and automatically free its memory when it goes out of scope.
There is no any need to set the pointer to NULL in statement
myPtr = NULL;
On the one hand this prevents the program from an execution error if you will try to free the pointer the second time. On the other hand it maybe hides the bug code where you try to free the pointer the second time.
So whether you need to set the pointer to NULL depends on the program design.
If you are speaking about C++ then it would be better if you would use never C functions malloc and free. Consider using of smart pointers as for example std::shared_ptr.
Setting the pointer back to "NULL" will only be useful if you need to reuse it again later and run checks on it like "if(myPtr) { [...] }". If you don't plan on reusing this specific pointer, you can leave it to whatever his value is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With