-1

I just want to know When and Why we must use the malloc and allocate sufficient memory.

Should I use in destination pointer or what?

  • 1
    As your question is tagged with c++, I would say you very rarely need to use `malloc`. Prefer `std::make_unique`, `std::make_shared` and sometimes `new`. Not sure if you are asking when `malloc` specifically should be preferred or if you are asking about dynamic memory allocation in general. – François Andrieux Jul 14 '17 at 14:13
  • 6
    if you ask that question, the answer is: never – 463035818_is_not_an_ai Jul 14 '17 at 14:13
  • 3
    In C++? You should never call `malloc` in C++. In most situation it's simply wrong and will lead to *undefined behavior*. – Some programmer dude Jul 14 '17 at 14:15
  • More generally, it seems to me that you could need [a good beginners book or two](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to read. – Some programmer dude Jul 14 '17 at 14:15
  • If you know what you're doing and you decide that malloc is the right tool (e.g. inside custom allocators). I don't see any use for it in regular C++ code. – stefaanv Jul 14 '17 at 14:20
  • I wonder was this the actual question (when to use malloc in c++) or was it more about when to use dynamic memory in general?? – drescherjm Jul 14 '17 at 14:43

2 Answers2

3

In C++, the use of malloc/free is discouraged. You should use new/delete instead, which allocate a block of memory AND initialize it (default construction). Since C++11, even new/delete should be avoided and you should use smart pointers like std::unique_ptr instead. However, malloc might still be useful for raw buffers and memory pools, but only in large scale applications where each cycle counts. For normal cases like yours (I suppose), don't even think about it.

1

You shouldn't use malloc in C++. Use new/delete or new[]/delete[] instead or use a smart pointer like std::shared_ptr<T>().

malloc does not call an objects constructor and malloc must be undone with free, (which does not call an objects destructor). On top of that, malloc is not type-safe as it returns a void*. Unless you have good reason, stay away from malloc.