C++ Why is my program throwing an exception?

112 Views Asked by At

I'm new to programming and I'm trying to code a function that gets the shortest string from a list, but everytime I run it, visual studio shows an error "Exception thrown: read access violation". Where is the mistake?

#include <iostream>
#include <string>
using namespace std;

const string &shortest_string(initializer_list<string> strings) {
    string *shortest_one = nullptr;
    for (string string : strings) {
        if (shortest_one == nullptr) shortest_one = &string;
        else {
            if (string.size() < shortest_one->size()) shortest_one = &string;
        }
    }
    return *shortest_one;
}

int main() {
    cout << shortest_string({ "hello" , "my", "name", "is", "dan" }) << endl;
    return 0;
}
2

There are 2 best solutions below

3
On BEST ANSWER

You made variable with name that matches type name (string variable, string type?). Plus there is issue that you return pointer to object with local scope of life. That is UB. Using iterators your function would work like this:

const string shortest_string(initializer_list<string> strings) {
    if(!strings.size()) return string();
    auto shortest_one = strings.begin();
    for (auto it = shortest_one+1; it < strings.end(); it++   ) 
    {
        shortest_one = (it->size()< shortest_one->size()) ? it : shortest_one;
    }

    return *shortest_one;
}
1
On

if (shortest_one = nullptr) is not a comparison operation. It is an assignment, that sets shortest_one to nullptr. This operation evaluates to 0, so the if expression is equivalent to if (0), or if (false).

Then in the else block, you are using shortest_one->size() but shortest_one is null...

Try to use if (shortest_one == nullptr) instead.