Solved

malloc() in c++

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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…
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 clear a vector as well as how to detect empty vectors in C++.

717 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