Setting pointer to NULL before delete

时间:2016-02-12 20:19:13

标签: c++ pointers

So I stumbled upon this bit of code and while I've been coding in C/C++ for about 5 years now, I cannot fathom why anybody would want to do this. I understand why you'd want to set the pointer to -melf_i386 after deallocating memory, but I certainly don't understand why someone would want to do the opposite (looks like a memory leak to me).

Second, I'm pretty sure it's not necessary to check if the pointer is NULL before setting it to NULL and deleting it, as discussed here.

NULL

3 个答案:

答案 0 :(得分:5)

Double deleting an object can result in the destructor being called twice, so some people favor setting it to acceptable = 'scale_', 'shift_', 'reject_', 'dev_' kwds = {key[:-1]: {k.split('_', 1)[-1]: v for k, v in kwargs.items() if k.startswith(key)} for key in acceptable} after deletion. This prevents the destructor from being called on memory which could have been reallocated from the pointer's previous memory address.

As shown here though, setting to NULL before deleting is a memory leak. Fixed code without memory leak:

NULL

Note that calling delete on if( m_pio ) { delete m_pio; m_pio = NULL; } (or NULL in C++11), is legal so you code could just be written as this instead:

nullptr

答案 1 :(得分:1)

The author has wanted to write:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package virtualworld;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author MTAH
 */

public class Virtualworld {

    /**
     * @param args the command line arguments
     */

//to remove code from main, I have created separate methods
//myApp gets whatever methods are in run() to execute
    public static void main(String[] args) {
        // TODO code application logic here

        Virtualworld myApp = new Virtualworld();
        myApp.run();

    }

    private List<String> list;

    //run is a method that gets the methods createClone and createPet to run
    public void run() {

        createMenu();
        shoutOutCannedMessage();
        createClone();
        createPet();


    }

/*this is the createClone method, it takes input and manipulates the myclone class
it produces an output by plugging in the data taken to myclone class and 
produces the introduction
*/


    private void createMenu() {
        list = new ArrayList();
        list.add(0, " ");
        list.add(1, "1. Java is fun!");
        list.add(2, "2. Greece is famous for its archaeological history. ");
        list.add(3, "3. Spain has great churros and hot chocolate. ");
        list.add(4, "4. Sweden has beautiful architecture. ");
        list.add(5, "5. Choose Denmark if you love Lego! ");
        list.add(6, "6. South Africa has a great Safari option by Sun City!");
        list.add(7, "7. Japan is fun and filled with gorgeous cherry trees.");
        list.add(8, "8. The U.K. is a place with history right next to modernity");
        list.add(9, "9. This is a project for IT 511");
        list.add(10, "10. This was created by ");
    }

    private void shoutOutCannedMessage() {
        System.out.println("This is a list of options: ");
        int size = list.size();

        for (int i = 0; i < size; i++) {
            System.out.println(list.get(i));
        }

        int userNumber;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter number: ");
        userNumber = scanner.nextInt();
        System.out.println(list.get(userNumber));


    }


    private void createClone() {

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter your first name: ");
        String firstName = input.next();

        System.out.println("Please enter your last name: ");
        String lastName = input.next();

        myclone individual = new myclone(firstName, lastName);
        System.out.println(individual.introduction());

    }

/*this is the createPet method, it takes input and manipulates the pet class
it produces an output by plugging in the data taken to pet class and 
produces the pet's introduction
*/

    private void createPet() {

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the type of animal your pet will be (Ex. cat, dog, etc): ");
        String animalType = input.next();

        System.out.println("Please enter what color you want your pet to be (Ex. blue, green, brown, white):  ");
        String animalColor = input.next();

        System.out.println("Please enter your pet's name: ");
        String animalName = input.next();

        pet kind = new pet(animalType, animalColor, animalName);
        System.out.println(kind.petIntroduction());


    }


}

but messed the lines and there is bad bug. Assigning delete m_pio; m_pio = NULL; after NULL is good prectice to protect the variable from another delete.

答案 2 :(得分:0)

Obviously we can't discern what the original author had intended.

On a side note, you'd be surprised at the amount of people I've worked with (even industry veterans) who have it in their head that System.Diagnostics.Process.Start("pathtohtmlfile.html"); ing or deleteing free is somehow a bad thing that needs to be guarded against, despite that there are no consequences for it. It just ends up creating a huge tidal wave of unnecessary checks, especially when the developer in question is especially fond of wasting their time manually managing memory.