11, dynamic memory allocation malloc / free

Dynamic memory allocation

Memory application and release two functions to achieve: malloc / free.

malloc memory applications

#include <stdlib.h>
 int main () 

{ 
    int * P = ( int *) the malloc ( 100 * 4 ); // Application 100 * 4 bytes 

    for ( int I = 0 ; I < 100 ; I ++ ) { 
        P [I] = I * I;    // use this memory 

    } 
    return  0 ; 
}

 

Note that, to apply the size in bytes of space, the application itself responsible for calculating the total number of bytes needed. For example, to store 100 int, then the size of the required space should be 400 bytes, can be used malloc (100 * 4) or malloc (100 * sizeof (int)) to specify the size.

Malloc return value pointing to a piece of application memory, the application needs to force it into the specified data type. This memory array and no essential difference between the use of the same.
    free release memory

#include<stdlib.h>
void free(void*ptr);

 

Example: a citizen expressed by Citizen, expressed a car with a Car. At first a citizen without a car, but the future may have a car.

#include <stdlib.h> 

#include < String .h> struct Car { char Maker [ 32 ]; // Manufacturer int . price;       // Price 
}; struct Citizen { char name [ 32 ];   // Name int deposite;    // deposit 
    car * cAR;        // when NULL indicates no car 
}; // definition of an object: the car did not start. 
Shaofa Citizen = { " liyanyan " , 100 , NULL}; //



    

    




    

    



 




 

Later, he could buy a car. 

void Buy (Citizen * owner) { 

    // create an object 

    Car * CAR = (Car *) the malloc ( the sizeof (Car)); 

    strcpy (CAR -> Maker, " the BMW " ); 

    CAR ->. price = 10 ; 

    // save this object (or rather remember pointer) 

    owner -> = cAR cAR;    // car with 

    owner -> deposite - of car-=>. price;   // money was gone 

} 

// One day, this car It will be scrapped. 

void discard (Citizen * owner, Citizen * OTHER) { 

    Car * = owner- CAR> CAR;

    CAR ->. price * = 0.5 ;   // half-price sale 

    OTHER -> = CAR CAR;    // others have the car 

    owner -> deposite of Car-+ => . price; 

    // not free (CAR); // can not free this car is in the hands of others 

    owner -> cAR = NULL;   // back to the car-free status 

}

 

Guess you like

Origin www.cnblogs.com/QLEO/p/12286027.html