首页 > 解决方案 > 读取变量时出错:无法访问地址 x 处的内存

问题描述

所以可能是一个愚蠢的问题,但我对 C++ 不是很熟悉,所以......然后我运行这段代码,它在点击第二个 if 后崩溃,没有错误代码

#include <fstream>
#include <string>

#include "day.cpp"
#include "appointement.cpp"

using namespace std;
// Flags are placed as constants to easy access
const string mod="mod", lst="lst", rmv="rmv";
const string add="add", title="-t", date="-d";
bool ispresent (string command, string flag)
{
    int pos=command.find(flag);
    if (pos==-1)
    { 
        return false;
    }
    else
    {
        return true;
    }
}

int main()
{
    
    string command;
    cout << "Hi, send command:";
   //this is analysed and searched for flags
    cin >> command;
    //if the "add" is present, create a new event (userEvent)
    if (ispresent (command, add))
    {
        cout << "add triggered";
        ofstream saveFile;
        saveFile.open("/tmp/.calendar/saveFile.txt");
        appointement userEvent; 
        // this test always fail
        if (ispresent(command, title))
        {      
            //search for "-t" to add the title to the event      
            cout << "-t triggered";
            int flag=command.find("-t")+2;
            cout << "placed after -t";
            userEvent.setTitle(command.substr(flag,command.find(" ")));
            cout << "title set";
            // search for "-d" to add the date to the event
            if (command.substr(flag,flag)==date)
            {
                int flag=flag+2;
                userEvent.setTimeNotification(command.substr(flag+2, command.find (" ")));
            }
        }
        
    }
    
    return 0;
}

起初我以为测试不好,但是将其运行到 gdb 中给了我这个错误:

   ispresent (command=<error reading variable: Cannot access memory at address 0x6a9b6f7a416ff400>,
   flag=<error reading variable: Cannot access memory at address 0x3>) at main.cpp:13

我知道对变量的访问权有些问题,但我不明白实际发生了什么......我在这里检查类似的问题,但似乎没有人解释实际上正在发生的事情以及如何修复/避免它在未来

标签: c++memory-management

解决方案


So after @molbdnilo pointed out, my "command" isn't actually the way it thought it was and only contain the first string in the command (each white space breaks my command in multiples strings). So the issue is then i call the second test, it cannot work because my "command" variable is smaller than the position i tried to test, so then the program call the memory space where the continuation of the variable should be i get an memory error since this program is not allowed to use this memory space.


推荐阅读