free() & delete()

hi
what is the mean of free() & delete() operators?
what is the difference between these?
Please explain these with examples
closed account (zb0S216C)
free( ) is used on resources allocated by malloc( ), or calloc( ). delete/delete[ ] is used on resources allocated by new/new[ ]. free( ) is used in C, where delete/delete[ ] is used in C++. Also, delete has two ways of calling it. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Using free( ):
int *pResources( malloc( 2 * sizeof( int ) ) );
free( pResources );
pResources = NULL;

pResources = ( malloc( sizeof( int ) ) );
free( pResources ); // No different from the previous call.
pResources = NULL;

// Using delete/delete[ ]:
int *pResources( new int[ 2 ] );
delete [ ] pResources;
pResources = NULL;

pResources = ( new int( 0 ) );
delete pResources; // Different from the previous call.
pResources = NULL;

As you can see in the code example above, free( ) can delete an array of resources, or a single resource. With delete/delete[ ], you have to tell it what type of block it's deleting. For example, if use delete[ ], you're deleting an array. If you use delete, you're deleting a single object.

A final note: Don't use malloc( ), or calloc( ) with delete/delete[ ], and don't use new/new[ ] with free( ).

Wazzak
Last edited on
Thank you
nice example...
Topic archived. No new replies allowed.