Snowman08
Snowman08

Reputation: 425

Expression invalid null pointer

I am having some issues with my program, what I want to do is generate a md5 password which then save it to a text file and this part is not working for me, ("Expression invalid null pointer") any help would be greatly appreciated.

C++ Visual Studio 2015

main.cpp

#include <iostream>
#include <istream> 
#include <string> 
#include <sstream>
#include <fstream>
#include <iterator>
#include "s_encrypt.h"
#include "encrypt_copy.h"


using namespace std;




int main(int argc, char *argv[])
{
    string password = "";

    cout << "Please enter a password to be encrypted\n";
    getline(cin, password);


    cout << "MD5 Encryption of " << password << " " << "is this" << " " << md5(password);

    cout << "Saving MD5 generated password to text file";

    std::string p = md5(password);

    CopyEncryptedPw(p);

    return 0;

}

encrypt_copy.cpp

#include <istream>
#include <iostream>
#include <fstream>
#include <string>
#include "encrypt_copy.h"

using namespace std;

std::string CopyEncryptedPw(std::string pass)

{
    fstream outfile;

    outfile.open("C:\encrypted_pass.txt", ios::out);
    outfile << pass;
    return 0;
}

encrypt_copy.h

#pragma once
#ifndef ENCRYPT_H
#define ENCRYPT_H


std::string CopyEncryptedPw(std::string pass);

#endif 

enter image description here

Upvotes: 0

Views: 712

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35454

There are two issues with your code:

Issue 1:

outfile.open("C:\encrypted_pass.txt", ios::out);

If we assume that your OS is Windows, this should be:

outfile.open("C:\\encrypted_pass.txt", ios::out);

Also, the forward slash can be used for the standard stream functions:

outfile.open("C:/encrypted_pass.txt", ios::out);

Issue 2:

You're returning 0 for a function that is supposed to return a std::string.

std::string CopyEncryptedPw(std::string pass)
{
    //...
    return 0;  // <-- This is bad
}

This code exhibits undefined behavior on return, since what will happen is that a 0 is assigned to the std::string return value, and assigning 0 to a std::string is undefined behavior.

Either return a string type (or a type that is convertible to a std::string), or return int:

int CopyEncryptedPw(std::string pass)
{
    fstream outfile;
    outfile.open("C:\\encrypted_pass.txt", ios::out);
    outfile << pass;
    return 0;
}

You could also have a void function that doesn't return anything, but you probably want an int return value for example, to return an error code (or OK indicator).

Upvotes: 4

Related Questions