Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use malloc and free memory?

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.

like image 810
Ono Avatar asked Jul 04 '14 13:07

Ono


3 Answers

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 doubles that will grow its storage if required and automatically free its memory when it goes out of scope.

like image 108
simonc Avatar answered Nov 15 '22 08:11

simonc


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.

like image 21
Vlad from Moscow Avatar answered Nov 15 '22 08:11

Vlad from Moscow


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.

like image 27
Ely Avatar answered Nov 15 '22 07:11

Ely