【问题标题】:Why m I getting a segmentation error when my code gives correct output?当我的代码给出正确的输出时,为什么会出现分段错误?
【发布时间】:2021-08-05 03:54:31
【问题描述】:
#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 在 ?? ()

要启用此文件的执行,请添加 添加自动加载安全路径 /usr/local/lib64/libstdc++.so.6.0.25-gdb.py 行到您的配置文件“//.gdbinit”。

要完全禁用此安全保护,请添加 设置自动加载安全路径 / 行到您的配置文件“//.gdbinit”。

有关此安全保护的更多信息,请参阅 GDB 手册中的“自动加载安全路径”部分。例如,从 shell 运行: info "(gdb)自动加载安全路径"*

【问题讨论】:

  • 你给你的程序提供了什么导致这个崩溃的输入?请编辑您的问题以添加此信息。
  • 哪里崩溃了?在什么输入上?
  • When choice is 3 you have: cout&lt;&lt;itr-&gt;second&lt;&lt;endl; what happens if name was not found?你假设它总是被找到。选择 2 时同样的问题。

标签: c++


【解决方案1】:

你的程序的输入是什么?

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    相关资源
    最近更新 更多