c++ - 读取变量时出错:无法访问地址 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
我知道对变量的访问权有些问题,但我不明白实际发生了什么......我在这里检查类似的问题,但似乎没有人解释实际上正在发生的事情以及如何修复/避免它在未来
解决方案
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.
推荐阅读
- numpy - pyqgis:从列表中创建多层(自动)
- c++ - 尝试运行 CusolverSSgels 测试用例,但它不起作用
- flutter - Flutter Https 未处理异常:参数无效
- magento2 - 状态码:安装 Magento-2 后出现 500 错误。我无法查看我的主页,也无法登录到后端
- lua - 如何在路由请求之前从 haproxy 中的 lua 发送 https 请求?
- data-structures - 展开树中的有序继任者和前任者
- reactjs - 如何让 KeycloakProvider 包装 next-redux-wrapper?
- spring-jdbc - 使用带参数的 SET_JSON 时,NamedParameterJdbcTemplate 语法错误
- reactjs - 托管在通过 Azure Front Door 访问的存储帐户上的静态网站未正确加载
- javascript - Electron - 自动更新程序:有没有办法只安装更新的功能而不是重新安装整个应用程序