簡體   English   中英

如何修復分段錯誤:C++ 中的 11?

[英]How to fix a segmentation fault: 11 in c++?

我目前正在開發一個程序,該程序使用模板函數從數字數組中獲取模式。 在我的 macOS 上使用 g++ 編譯代碼沒有問題(即沒有錯誤、警告等)。 但是,當我運行代碼時,我在終端中得到了這個輸出:

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"

我得到了那個錯誤(不是分段錯誤)

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,因此拋出異常並且沒有捕獲器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM