Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>whats wrong with the code.</p> </blockquote> <p>Everything except <code>int i;</code></p> <p>The second line attempts to convert an integer to a pointer. In special circumstances, you could force that past the compiler with <code>reinterpret_cast</code>; but the program would only behave correctly if the integer somehow contained a valid pointer value. (<strong>UPDATE</strong>: the question has now been edited to take the address of <code>i</code> instead; so this line is no longer wrong).</p> <p>The third line attempts to delete invalid memory using an invalid pointer type.</p> <blockquote> <p>What it should be.</p> </blockquote> <p>Something else. Without knowing what you want to do, it's impossible to say. Perhaps you want:</p> <pre><code>int i; void * ptr = &amp;i; // Points to `i`, losing type information. </code></pre> <blockquote> <p>Operator <code>delete</code>, applied to <code>void*</code> argument.</p> </blockquote> <p>That's always wrong. You must only <code>delete</code> an object you previously allocated with <code>new</code>; and the pointer must be to the correct type.</p> <p><sub>(or to a base class, if it's a class type with a virtual destructor)</sub></p> <p>So the following would be correct; but pointless unless you have a good reason for dynamic allocation:</p> <pre><code>int * ptr = new int; delete ptr; </code></pre> <p>And of course, if you're writing code that should be robust against memory leaks and runtime errors, you should manage all dynamic memory using <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> types such as containers and smart pointers. So, if you need to a dynamic object, you should do:</p> <pre><code>std::unique_ptr&lt;int&gt; ptr(new int); </code></pre> <p>if you want a to delete it at the end of the current scope or move it into another scope; or</p> <pre><code>auto ptr = std::make_shared&lt;int&gt;(); </code></pre> <p>if you want to share ownership between more than one scope. In either case, the pointers will delete the object automatically once you've finished with it.</p>
    singulars
    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