我目前正在研究一个程序,该程序使用模板函数从数字数组中选取模式。在我的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);
}
我获得了我的代码here的一部分
预期的输出是这样:
"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,因此引发了异常并且没有捕获器。