Solved

malloc() in c++

Posted on 2003-11-24
3
439 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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
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 additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

746 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now