读取对象后的不良访问权限

问题描述 投票:0回答:1

我正在为一个学校项目制作密码管理器,如果在上面使用所有贴纸,都将产生巨大的保修失效。目的是能够对程序中的数据进行CRUD并将其以“加密”形式写入磁盘。

我有一个基本类型和子类型的动态数组,可以使用Library :: WriteToFiles()将其写入内存,并使用Library :: ReadFromFiles()从内存中读取。在我总是写然后立即读回内存的调试设置中,所有这些都很好用。

int main() {
bool debug = true;
if (debug) {

    Library library = Library();
    library.Add(new Password("Outside", "yobro"));
    library.Add(new Password("Wut", "idk"));
    library.Add(new UsernameLogin("Yo", "M8", "James May"));

    library.Print();

    cout << endl;

    library.WriteToFiles();
    library.ReadFromFiles();

    library.Print();
    return 0;

}

但是当我注释掉Write调用时,我从read函数的这一位获得了错误的访问权限

void Library::ReadFromFiles() {
this->Clear();

ifstream baseFileObject;
ifstream usrNameFileObject;

baseFileObject.open("base.txt");
while (true) {
    if (baseFileObject.eof()) break;
    Password* password = new Password();
    baseFileObject.read((char*) password, sizeof(*password));
    if ( ! password->IsEmpty()) { // <- Trying to call IsEmpty() throws a BAD ACCESS
        Add(password);
    }
}
baseFileObject.close();

[当我尝试调用Password类中的其他非虚拟函数时,它们运行得很好。 IsEmpty()在读取之前也可以正常运行。我检查了指针,它始终保持不变。文件正确打开,并且数据被读入对象。

最让我感到困惑的是,为什么我已经在那个执行中编写了它,为什么它仍然起作用。如果读入这样的对象会破坏vtable,那么为什么有时它会起作用?

编辑:密码类具有3个变量。两个弦和一个布尔。没有指针。这是公共功能。我只有虚函数有问题。

public:
virtual int Type();
virtual string ToString();
virtual bool IsEmpty();
virtual bool Encrypt(unsigned int key);
virtual bool Decrypt(unsigned int key);

[[nodiscard]] bool isEncrypted() const;

[[nodiscard]] const string &getPassword() const;
void setPassword(const string &newPassword);

[[nodiscard]] const string &getLocation() const;
void setLocation(const string &newLocation);

int PasswordStrength();
c++ virtual-functions vtable
1个回答
0
投票

已经明确这一行:

baseFileObject.read((char*) password, sizeof(*password));

仅不适用于我的用例。序列化是显而易见的,可扩展的,理想的解决方案,但是由于这是一个学校项目,因此我打算将老式的文本写入文件并使用sstream或类似的东西将其解析回。

感谢您的帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.