Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • Last Modified:

memory question

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
dib
Asked:
dib
1 Solution
 
Blondie050798Commented:
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
 
yonatCommented:
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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now