首页 > 解决方案 > 当我的代码给出正确的输出时,为什么会出现分段错误?

问题描述

#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"*

标签: c++

解决方案


你的程序的输入是什么?

当您访问内存位置之外的内存时,会发生分段错误。

我怀疑选项 2 和选项 3 随时可能导致分段错误。因为即使地图中不存在输入名称,您仍试图更改其值。它不安全。


推荐阅读