Solved

memory question

Posted on 1998-05-11
2
266 Views
Last Modified: 2010-04-10
What is the exact difference between

char *pBuf = new char[10];

and

char *pBuf = (char*)malloc(10);

both will allocate space on the heap?!
0
Comment
Question by:dib
2 Comments
 
LVL 1

Accepted Solution

by:
Blondie050798 earned 50 total points
ID: 1175610
Specifically for MS VC++, new eventually calls malloc, so architecturally there is no difference. However, VC++ and I imagine all other compilers create clever debug versions of new to trap memory reuse, leaks etc. You have also given a very simple example, new comes into its own as a flexible allocator designed for allocating classes not as a char allocator. (nb I'd probably use an automatic or static array anyway!)
0
 
LVL 5

Expert Comment

by:yonat
ID: 1175611
One difference is that "new" can be re-defined by the programmer. Another, is that it is type safe (no need for the casting, no need to calculate the size if you want to allocate an array of amything bu char). But the most important difference is when you need to allocate OBJECTS, and not just plain chars: new will call the object's constructor, while malloc will not.
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question