How to correctly use malloc and free memory?

c, c++, free, malloc, secure-coding

Solution

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.

Problem

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.

Original source

Related problems