delete[ ] with malloc or free [ ] with new()

V

valdano

I just want to know what is the best way to allocate and deallocate a
memory
with out causing any kind of memory leaks, crashes.
should I use Malloc and then use delete[ ]
for exp:
char *buffer = (char *) malloc(90* sizeof(char));
//do some stuff
delete buffer[];

or it is better to use
char *buffer = new char[90* sizeof(char)];
//do some stuff
free buffer[] //or delete buffer[]

also if anybody has any more tips i can use during building my program
in order to prevent it from crashing due to memory misuse that would
be great


many thanks
 
J

James Aguilar

Use malloc with free, and new with delete. No other combinations are valid. In
C++, it is generally standard practice to use new and delete.

- JFA1
 
V

Victor Bazarov

valdano said:
I just want to know what is the best way to allocate and deallocate a
memory
with out causing any kind of memory leaks, crashes.

The best way to avoid memory leaks is to deallocate any memory you
allocate, as soon as you don't need it any longer.
should I use Malloc and then use delete[ ]

No, never. Why ask? Use 'delete' for pointers from 'new', use
'delete[]' for pointers from 'new []', use 'free' for pointers from
'malloc'.
for exp:
char *buffer = (char *) malloc(90* sizeof(char));

'sizeof(char)' is always 1. Save yourself some typing.
//do some stuff
delete buffer[];

Wrong syntax and wrong operator. Use

free(buffer);
or it is better to use
char *buffer = new char[90* sizeof(char)];

'sizeof(char)' is always 1. Save yourself some typing.
//do some stuff
free buffer[] //or delete buffer[]

There is no "free buffer[]" syntax. There is no "delete buffer[]".
You should use

delete[] buffer;

here.
also if anybody has any more tips i can use during building my program
in order to prevent it from crashing due to memory misuse that would
be great

Get a good book and study.

V
 
C

Chris Jefferson

4 simple rules which will cover 99% of cases :)

1) If you malloced it, make sure you free it
2) If you newed it, make sure you delete it
3) If you new[]ed it, make sure you delete[] it
4) If the compile allocated the memory for you, the compiler will
deallocate it for you.
 

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,781
Messages
2,569,615
Members
45,296
Latest member
HeikeHolli

Latest Threads

Top