?
Solved

malloc() in c++

Posted on 2003-11-24
3
Medium Priority
?
447 Views
Last Modified: 2010-04-02
I was told malloc() is c and not c++. Is this correct ??
If so, how should I do a malloc() in c++ ?
0
Comment
Question by:teuntje
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 44

Accepted Solution

by:
Karl Heinz Kremer earned 240 total points
ID: 9814059
You can use malloc() in C++ as well, but the C++ way of allocating memory is with new.

To get a new instance of a class you would do the following:

CMyClass * myClass;

myClass = new CMyClass;

// ... do somethign with the object

delete myClass; // this "frees" the object again.

Does this answer your question?
0
 
LVL 2

Author Comment

by:teuntje
ID: 9814065
yes.
thank you.
0
 
LVL 4

Expert Comment

by:void_main
ID: 9816917
There is even more:

if you want to allocate or delete an ARRAY you should use this:

char *myArray = new char[number];

to access element 20 use
*myArray[19] = value;

and

delete[] myArray;       // DO NOT insert a number here, C++ will handle this internal.

And its correct: c++ DOES accept malloc() and free(), but there is no guarantee (this depends on your compiler -> it works with my Borland Compiler but I prefer new and delete)

best regards
void_main
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

764 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