Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use malloc() in C++ [closed]

Tags:

c++

How to use malloc() in C++ program?

like image 971
dato datuashvili Avatar asked Jul 11 '10 08:07

dato datuashvili


2 Answers

You shouldn't use malloc in C++. You should use new instead. In fact, you probably shouldn't be using new as well (for most basic programming in C++). But still a basic example is declaring an array: int* array = new int[n]. This will allocated room for n integers and return a pointer to the address of the first one. Please note that you must explicitly call delete[] to free this allocation.

like image 79
Shiroko Avatar answered Oct 05 '22 21:10

Shiroko


Mostly, you shouldn't use it at all. C++ provides the new and delete operators for memory management, and even delete can be largely avoided by using smart pointers such as boost::shared_ptr from the Boost library.

Example:

// malloc
Duck* duck = (Duck*)malloc(sizeof(Duck));

// new
Duck* duck = new Duck();

Also note that, if the Duck class has a non-trivial constructor, then new is almost mandatory. (Almost, because you could use malloc with placement new, but that would be getting us off the main track).

like image 44
Marcelo Cantos Avatar answered Oct 05 '22 21:10

Marcelo Cantos