Dan
Dan

Reputation: 325

C++ function overload cause seg fault

I have struct called Set.

struct Set {
string name;
string value;
bool is_condition;
bool is_bool_val; };

I have to store many of these 'Set' structures, so I am using a vector.

vector<Set> list;

For context, I am storing data about a mobile device such as an iPhone. A list of Set's describes one device! For example, an instance of set could have the following...

Set phone;
phone.name = "Serial Number";
phone.value = "FLMJ0000GGGG";
phone.is_condition = false;
phone.is_bool = false;

is_condition, tells me that this instance of Set needs to store either 'Good' or 'Bad' as the value. is_bool, tells me that the instance of Set needs to store a boolean value. See the below example.

Set device_wiped;
device_wiped.name = "Device Wiped";
device_wiped.is_bool = true;

Extrapolating from is_bool allows me to get input of either true or false, meaning the device either has, or has not been wiped (restored to factory settings).

I am using an overloaded wrapper function called new_set to create my Set elements, which are stored in my 'list' vector.

Set new_set(string name, const bool is_bool, const bool is_condition) {
    Set set;
    set.name = name;
    set.is_bool = is_bool;
    set.is_condition = is_condition;
    return set;
}

Set new_set(string name, const bool is_bool) {
    return new_set(name, is_bool);
}

Set new_set(string name) {
    return new_set(name, false, false);
}

I have three wrapper functions as this makes it easier to implement (I only want to write parameters if I have to!). This compiles fine, but I can not run. Crashes on a segmentation fault. Let me know if you need the entire code.

For now I am not needing to store data in the Set.value or Set.condition fields. I just want to initialise them all with a name the booleans.

Upvotes: 2

Views: 134

Answers (1)

hant0508
hant0508

Reputation: 556

The problem is in the second function:

Set new_set(string name, const bool is_bool) {
    return new_set(name, is_bool);
}

There's an endless recursion here. I guess you meant return new_set(name, is_bool, false); or return new_set(name, is_bool, true);.

By the way, your three functions can be simplified into one as follow (as @SirGuy mentioned):

Set new_set(string name, const bool is_bool = false, const bool is_condition = false) {
    Set set;
    set.name = name;
    set.is_bool_val = is_bool;
    set.is_condition = is_condition;
    return set;
}

Upvotes: 4

Related Questions