How to use malloc and free memory?

I am wondering what the correct / standard way to use malloc is for free. Do I need to set the NULL pointer after free? Basically, which of the following two methods is correct?

double* myPtr = (double*)malloc(sizeof(double)*5);
.....
free(myPtr);

or

double* myPtr = (double*)malloc(sizeof(double)*5);
.....
free(myPtr);
myPtr = NULL;

Or should these be other ways to use malloc for free? Thank.

+4
source share
7 answers

Both are beautiful. The only difference is that the previous approach will work if you try to release a myPtrsecond time.

Depending on the language you use, the string mallocmay be slightly matched.

sizeof(*myPtr) . C,

double* myPtr = malloc(sizeof(*myPtr)*5);

WhozCraig, ++,

 std::vector<double> ar(5);

5 double, , , , .

+10

NULL

myPtr = NULL;

, , . , , .

, NULL, .

++, , C- malloc . , , std:: shared_ptr.

+7

"NULL" , "if (myPtr) {[...]}". , .

+3

, , ( C malloc, ++ ). myPtr NULL free. , .

+2

. NULL, , SEGFAULT .

.

double * ptr = malloc(sizeof(double) * 42 );
ptr[0] = 1.2; // OK
free (ptr); // OK
ptr = malloc(sizeof(double) * 13); // It OK. You don't need to set pointer to NULL

.

void assign(ptr)
{
    if( ptr != NULL) ptr[0] = 1.2;
}

double * ptr = NULL;
assign(ptr); // All OK, method will not pass check
double * ptr = malloc(sizeof(double) * 42);
assign(ptr); // OK, method will pass check and assign
free(ptr);
// ptr = NULL; // If we don't do this ....
.... a lot of code and 666 lines below ... 
assign(ptr); // BAH! Segfault! And if You assign ptr=NULL, it would not a segfault
+2

free:

free() , - . . , , .

C :

double* myPtr = malloc(sizeof(double)*5);
.....
free(myPtr);
myPtr = NULL; 
+1

malloc/free, . ,

  • "" ( ),

, malloc/free, , .

,

 {
   double myPtr[5];
   ...
 }

 {
   double* myPtr = (double*)malloc(sizeof(double)*5);
   ...
   free(myPtr);
 }

, , "", . , , , "". , "", ; , .

+1

Source: https://habr.com/ru/post/1547172/


All Articles