c++ - 当我的代码给出正确的输出时,为什么会出现分段错误?
问题描述
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
map<string,int>m;
string name;
int choice, marks;
while(n>0)
{
cin>>choice>>name;
if(choice==1)
{
cin>>marks;
map<string,int>::iterator itr=m.find(name);
if(itr==m.end())
{
m.insert(make_pair(name,marks));
}
else{
itr->second=itr->second+marks;
}
}
else if(choice==2)
{
map<string,int>::iterator itr=m.find(name);
itr->second=0;
}
else if(choice==3){
map<string,int>::iterator itr=m.find(name);
cout<<itr->second<<endl;
}
n--;
}
return 0;
}
- 从解决方案中读取符号...完成。
[新 LWP 144748] [启用使用 libthread_db 进行线程调试]
使用主机 libthread_db 库“/lib/x86_64-linux-gnu/libthread_db.so.1”。核心是由“./Solution”生成的。
程序因信号 SIGSEGV、分段错误而终止。#0 0x00007f4200000000 在 ?? ()
要启用此文件的执行,请将 add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py 行添加到您的配置文件“//.gdbinit”。
要完全禁用此安全保护,请将 set auto-load safe-path / 行添加到您的配置文件“//.gdbinit”。
有关此安全保护的更多信息,请参阅 GDB 手册中的“自动加载安全路径”部分。例如,从 shell 运行: info "(gdb)Auto-loading safe path"*
解决方案
你的程序的输入是什么?
当您访问内存位置之外的内存时,会发生分段错误。
我怀疑选项 2 和选项 3 随时可能导致分段错误。因为即使地图中不存在输入名称,您仍试图更改其值。它不安全。
推荐阅读
- java - SQL Java中的参数索引超出范围使用phmyadmin
- c# - 像本地文件一样加载远程 ZIP 文件的 HTTP 流实现 - DotNetZip
- apache-nifi - Jolt:连接数组值
- mysql - 将图像从 MySQL 数据库获取到 PictureBox(vb.net)时出现“参数无效”错误
- c++ - 我得到的 lcounter 是正确的,但 pcounter 是像 32751 这样的随机值。我不认为它是未初始化的。任何人都可以解释这个问题吗?
- excel - 有没有办法缩短 Excel OR 函数?
- java - 将 POM 文件属性值读入 "
.properties 文件 - xml - spring boot XML 正在填充额外的标签
- python - 了解python程序
- node.js - NodeJS 使用 Socket.IO 对 POST 的响应