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 (ie no errors, warnings, etc.). However when I run the code I get this output in the terminal:
Segmentation fault: 11
Here is the code that I have:
#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);
}
I got part of my code here
The expected output is this:
"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
So
if (sizeof(result) > 1) throw std::range_error{ 0 };
else {
return result;
}
}
is what causes the problem because sizeof(result)
returns 4 for int result
, hence the exception is thrown and there is no catcher.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.