What's the differences between free() and delete?

D

Daqian Yang

Hello,

for example,

int *temp = int[256];

I wont' use "temp" anymore, so how can I free it from memory? using free()
or delete temp; ? thx
 
H

Howard

Daqian Yang said:
Hello,

for example,

int *temp = int[256];

I assume you meant:

int* temp = new int[256];

right?

I wont' use "temp" anymore, so how can I free it from memory? using free()
or delete temp; ? thx

When you allocate using new [], delete using delete [], so use

delete [] temp;


-Howard
 
K

Karl Heinz Buchegger

Daqian said:
Hello,

for example,

int *temp = int[256];

I wont' use "temp" anymore, so how can I free it from memory? using free()
or delete temp; ? thx

:)

In the above you have a syntax error.
The funny thing is, that using free() or delete [] depends
exactly on what you left out by prodicung that syntax error.

But from the rest of that line, one can conclude that in reality
that should read:

int* temp = new int[256];

Rule: new goes with delete
new [] goes with delete []
malloc goes with free
calloc goes with free

Since you have new [] in the above, the correct
memory release reads:

delete [] temp;


Usual post scriptum: Why don't you use std::vector? Much simpler
in the long run.


#include <vector>

int main()
{
std::vector temp(256);

// Look Ma. I don't have to worry about freeing the memory
// std::vector does all this by itself

}
 
J

jeffc

Daqian Yang said:
Hello,

for example,

int *temp = int[256];

I wont' use "temp" anymore, so how can I free it from memory? using free()
or delete temp; ? thx

malloc() and free() go together, and new and delete (or delete []) go
together. Never mix and match.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top