Lucas Mezalira
Lucas Mezalira

Reputation: 183

Segmentation fault (core dumped) C++ error

I get the "Segmentation fault (core dumped)" error with the following code:

#include <iostream>
#include <cstring>

template <class T>
T maxn(T* elements, int n);

template <> const char* maxn <const char*>(const char* elements[], int num);

int main(){
    using namespace std;

    //Using template
    int num[6] = {2, 3, 4, 5, 6, 22};
    double num2[4] = {16.6, 10.5, 2.3, 1.1};

    int larg = maxn(num, 6);
    double larg2 = maxn(num2, 4);
    cout << larg << endl << larg2 << endl;

    //Using specialization
    const char* pps[5] = {"Hello", "There", "I", "am", "me"};
    const char* largest = maxn(pps, 5);
    cout << largest << endl; 
    return 0;


}    

//return largest element in an array of T of n elements
template <class T>
T maxn(T* elements, int n){
    T largest = 0;
    for (int i=0; i<n; i++)
        largest = elements[i] > largest ? elements[i] : largest;
    return largest;
}    

//Returns address that points to the largest string
template <> const char* maxn <const char*>(const char* elements[], int num){
    int longest = 0;
    int i =0;
    for (i=0; i<num; i++)
        if (strlen(elements[i]) > strlen(elements[longest]))
            longest = i;
    return elements[i];
} 

I was getting the "warning: deprecated conversion from string constant to ‘char*" error but then I changed some char* arrays and function arguments to const char* and I got rid of that. Now the code compile and I get the following output:

22

16.6

Segmentation fault (core dumped)

The first two lines are right, but I can't understand what happens at the third one. Please help, thanks.

Upvotes: 0

Views: 1375

Answers (1)

awesoon
awesoon

Reputation: 33661

You return element out of bounds:

return elements[i];

Should be:

return elements[longest];

I can suggest declare i in for loop:

for (int i=0; i<num; i++)
//   ^^^^^^^

Then line return elements[i]; will throw a compile time error.

And, of course, you should give preference to built-in functions and containers :)

Upvotes: 5

Related Questions