Solved

malloc() in c++

Posted on 2003-11-24
3
443 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 60 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

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

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
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 clear a vector as well as how to detect empty vectors in C++.

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