Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unless you are forced to use C, you should <strong>never use</strong> <code>malloc</code>. Always use <code>new</code>.</p> <p>If you need a big chunk of data just do something like:</p> <pre><code>char *pBuffer = new char[1024]; </code></pre> <p>Be careful though this is not correct:</p> <pre><code>//This is incorrect - may delete only one element, may corrupt the heap, or worse... delete pBuffer; </code></pre> <p>Instead you should do this when deleting an array of data:</p> <pre><code>//This deletes all items in the array delete[] pBuffer; </code></pre> <p>The <code>new</code> keyword is the C++ way of doing it, and it will ensure that your type will have its <strong>constructor called</strong>. The <code>new</code> keyword is also more <strong>type-safe</strong> whereas <code>malloc</code> is not type-safe at all. </p> <p>The only way I could think that would be beneficial to use <code>malloc</code> would be if you needed to <strong>change the size of your buffer</strong> of data. The <code>new</code> keyword does not have an analogous way like <code>realloc</code>. The <code>realloc</code> function might be able to extend the size of a chunk of memory for you more efficiently. </p> <p>It is worth mentioning that you cannot mix <code>new</code>/<code>free</code> and <code>malloc</code>/<code>delete</code>.</p> <p>Note: Some answers in this question are invalid. </p> <pre><code>int* p_scalar = new int(5); // Does not create 5 elements, but initializes to 5 int* p_array = new int[5]; // Creates 5 elements </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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