Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>My problem is whether it is ok to push_back items to deque on this malloc pointer as it has allocated memory for pointer only?</p> </blockquote> <p>Normally, it is ok to push_back items into an object no matter how it was initialized (allocated dynamically or on the stack). In this case though, <code>p_Data</code> was allocated, but not initialized at all.</p> <p>To see this, you need to understand the difference between malloc and new:</p> <p>malloc is the C function that allocates a block of memory and returns a (void) pointer to it. The reason it exists in C++ is because C++ was initially compatible with C and able to use it's libraries (and nowadays it is required for backwards compatibility.</p> <p>new is the C++ operator that allocates a block of memory, interprets it as an object, and calls the constructor for that object transparently. The two functions are not interchangeable.</p> <p>When you allocate memory for an object, always use new. malloc will not call the constructor of your object (nor will free call the destructor of your object).</p> <p>Equivalent code:</p> <pre><code>class MyData { /* same as in your question */ }; // 1: normal C++ dynamic object allocation MyData* pMyData = new MyData(); // 2: allocate through malloc and call constructor through placement new void* block = (MyData*)malloc(sizeof(MyData)); // allocate sizeof(MyData) bytes MyData* pMyData = new(block) MyData(); // call constructor on block memory </code></pre> <p>This means that if you use malloc and free, your objects are not initialized, even though normally (intuitively) you'd expect them to be.</p> <p>TL:DR: Never use malloc and free in C++.</p> <blockquote> <p>After allocating for memory both pointers I used GetDequeMyDataSet() method on malloc pointer(p_Data)</p> </blockquote> <p>That shouldn't have worked. The malloc'd pointer should not be initialized (allocated yes, initialized no).</p> <p>On top of that, since you assign <code>p_Data = pMyData;</code>, your call to free will attempt to release memory already assigned by the delete statements (since both point to the same address).</p> <p>That should be seen as an access violation error.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload