如何解决分段错误:C ++中的11? [英] How to fix a segmentation fault: 11 in c++?

查看:109
本文介绍了如何解决分段错误:C ++中的11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个程序,该程序使用模板函数从一组数字中采用该模式.在我的macOS上使用g ++时,代码将毫无问题地编译(即没有错误,警告等).但是,当我运行代码时,会在终端中获得以下输出:

I am currently working on a program that takes the mode from an array of numbers using a template function. The code will compile with no problems using g++ on my macOS (i.e. no errors, warnings, etc.). However when I run the code I get this output in the terminal:

Segmentation fault: 11

这是我拥有的代码:

#include <stdexcept>
#include <cstdio>
#include <cstddef>

template<typename T>
T mode(const T* values, size_t length) {
    if (length < 0) throw std::out_of_range{ 0 };
    T result{};
    int number = values[0];
    int count = 1; 
    int countMode = 1;

    for (int i = 1; i < length; i++) {
        if (values[i] == number) {
            countMode++;
        }
        else {
            if (count > countMode) {
                countMode = count;
                result = number;
            }
            count = 1;
            number = values[i];
         }
    }

    if (sizeof(result) > 1) throw std::range_error{ 0 };
    else {
        return result;
    }
 }

int main() {
   const int arr[] = { 1, 4, 1, 2, 7, 1, 2, 5, 3, 6 };
   int arr_size = sizeof(arr) / sizeof(arr[0]);
   const auto result = mode<int>(arr, arr_size);
   printf("Mode = %d\n", result);
}

我在此处

预期输出是这样:

"Mode = 1"

推荐答案

我遇到了该错误(不是分段错误)

I got that error (not a segmentation fault)

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid

所以

 if (sizeof(result) > 1) throw std::range_error{ 0 };
    else {
        return result;
    }
 }

是导致问题的原因,因为sizeof(result)int result返回4,因此引发了异常并且没有捕获器.

is what causes the problem because sizeof(result) returns 4 for int result, hence the exception is thrown and there is no catcher.

这篇关于如何解决分段错误:C ++中的11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆