Search code examples
c++visual-studiovisual-studio-2017priority-queue

C++ priority queue push causing '...has stopped working' in Visual Studio 2017


Trying to write a simple program that creates a priority queue with C++ and adds a struct to it. Here is my code:

main.cpp:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <queue>

#include "defs.h"

using namespace std;

int main()
{ 
    priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority = {};

    /* Create Test Data */
    BinaryTreeNode* node1 = new BinaryTreeNode();
    node1->letter = ' ';
    node1->freq = 134;

    priority->push(node1);

    delete node1;
    delete priority;

    return 0;
}

In defs.h:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/* 
 * Node structure for Binary Tree 
 */
struct BinaryTreeNode
{
    char letter;
    int freq;
    BinaryTreeNode* left = NULL;
    BinaryTreeNode* right = NULL;
};

/* 
 * Comparison function for priority queue - prioritises lowest frequency letters
 */
struct nodeCmp
{
    bool operator() (const BinaryTreeNode* left, const BinaryTreeNode* right) const
    {
        return left->freq > right->freq;
    }
};

I am using C++ in Visual Studio 2017. I have initialized the queue with {} as I got another error if I did not. I have also tried dynamically allocating the char and int values that are being set for the node freq and letter but that also did nothing.

Removing the priority->push(node1) line in main prevents the '...has stopped working' from appearing.

I have also tried to Google and search stack overflow but have found nothing that fixes my problem.

Thanks in advance for any help.


Solution

  • This line does not create a priority queue:

    priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority = {};
    

    It creates a pointer which can point to a priority queue, but initially doesn't (it is a null pointer). When you then try to push something to the non-existing priority queue, you have a problem.

    The minimal fix is to actually create a priority_queue and point to it, i.e. change the above line to:

    priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority =
        new priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>;
    

    That should solve the crash (which is what 'has stopped working' means), although your program will not be what is normally considered good style (since, among other concerns, you don't even need dynamic allocation in this case).