Member Avatar for Search_not

I am writing to a file using a pointer variable that points to my File object, which includes the method used to write to my text file. When I try to delete the memory my program crashes... The error does not occur when I comment out the "delete file;" line. The rest of the code runs succesfully apart from the delete function. I want to avoid any possible memory leaks, please help.

Here's my code:

void change_registry_config(){
    try{
        file = new Files(file_path[1], WRITE_TO_FILE, IOS_OUT);   //predefined class

        set_data();   //function that overwrites the data in the vector

        file->write_file(*data);   //writes vector to file
    }catch(file_ex ex){
        SetWindowTextA(hEdit, ex.what());   
    }catch(exception e){

    }

    if(file != NULL){
        delete file;    //error occurs here, possible memory leak
    }
}

Code in header file used to write to file:

void Files::write_file(std::vector<std::string>& vect){

        if(!write_out->fail()){
            for(unsigned i = 0; i < vect.size(); i++){
                *write_out << vect.at(i) << std::endl;
            }
            write_out->close();  
        }else{
            file_ex er;   //custom error class extending std::exception
            er.set_msg("Could not access file");
            throw er;
        }
    }

The obvious first response is don't build it on the heap. You're creating it and destroying it all within the function change_registry_config, so just make it on the stack (i.e. don't use new) and you don't have to worry about memory.

Member Avatar for Search_not

Thanks, moschops

You also don't declare the type of the variable "file". That, and you should NOT use NULL in C++ except for void* types. Use 0 instead. That is valid for any type of pointer. Some compilers will complain about that, especially if warnings are enabled.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.