andrew fay andrew fay - 4 days ago 4
C++ Question

Strange output when attempting to print from an array of pointers c++

I'm attempting to create an array of pointers.

struct vertex
{
std::string id;
std::string name;
int networkID;
std::vector<adjVertex> friends;
bool visited;
};

struct hobbylist
{
std::string hobby;
std::vector<vertex*> list;
};

hobbylist * hobbies[HASHMAP_SIZE];


adding the user to the hobbies array:

int Graph::addUserToHobby(std::string hobby1, std::string id){
// initial key is based on the first 2 characters of the hobby name
int key = (hobby1[0] + hobby1[1]) % HASHMAP_SIZE;
cout << " initial hashmap key " << key << endl;
hobbylist *h = new hobbylist;
h->hobby = hobby1;
hobbies[key] = h;
}


my goal is to create an array of pointers with the hobbylist type, when attempting to print the contents of that array I end up with a very strange random symbol output:

GLIBC_2.2.5GLIBCXX_3.4.13GLIBCXX_3.4.14CXXABI_1.3GLIBCXX_3.4� P&y

I attempt to print it as so:

void Graph::displayHobbies(){
cout << "========================================\n";
cout << "DISPLAYING HOBBY INTERESTS =============" << endl;
for(auto const& value: hobbies)
{
cout << value->hobby << ":" << endl;
}
}


I was wondering if I am printing incorrectly or if I am adding the hobby to the hobbies array incorrectly.

Answer

You have at least two bugs.

hobbylist *h = new hobbylist;
h->hobby = hobby1;
hobbies[key] = h;

key is your hash key. If hobbies[key] already has a pointer, this is going to leak memory.

for(auto const& value: hobbies)
{
    cout << value->hobby << ":" << endl;
}

This assumes that every slot in the hobbies hash array contains a pointer. This is unlikely. If a particular value in hobbies has never been initialized (none of the previously inserted hobbies mapped to that hash key), the pointer will be NULL, and value->hobby will attempt to dereference a NULL pointer, resulting in undefined behavior. That's your likely crash.

Comments