Why is there a memory leak in this program and how can I solve it, given the constraints (using malloc and free for objects containing std::string)? [duplicate]

The important pieces of your code line by line… Allocate memory for one Person object: auto p = (Person*)malloc(sizeof(Person)); Construct a Person object in that already allocated memory via calling its constructor: p = new(p)Person(); Free the memory allocated via malloc: free(p); Calling the constructor via placement new creates a std::string. That string would be … Read more

Are new and delete still useful in C++14?

While smart pointers are preferable to raw pointers in many cases, there are still lots of use-cases for new/delete in C++14. If you need to write anything that requires in-place construction, for example: a memory pool an allocator a tagged variant binary messages to a buffer you will need to use placement new and, possibly, … Read more

Are ‘new’ and ‘delete’ getting deprecated in C++?

Neither snippet you show is idiomatic, modern C++ code. new and delete (and new[] and delete[]) are not deprecated in C++ and never will be. They are still the way to instantiate dynamically allocated objects. However, as you have to always match a new with a delete (and a new[] with a delete[]), they are … Read more

When and why to use malloc

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example, when you don’t know the amount of memory during compile time. One example should clear this. Say you know there will be maximum 20 students. So you can create an array … Read more

What is the difference between Static and Dynamic arrays in C++?

Static arrays are created on the stack, and have automatic storage duration: you don’t need to manually manage memory, but they get destroyed when the function they’re in ends. They necessarily have a fixed size at compile time: int foo[10]; Arrays created with operator new[] have dynamic storage duration and are stored on the heap … Read more

Difference between static memory allocation and dynamic memory allocation

This is a standard interview question: Dynamic memory allocation Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as ‘heap’ memory, although it has nothing to do with the heap data-structure ref. int * a = malloc(sizeof(int)); Heap memory is persistent until free() is called. In other words, … Read more