[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

malloc() in c++

Posted on 2003-11-24
3
Medium Priority
?
452 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
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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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.
Suggested Courses

834 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