Tim Johnsen
Tim Johnsen

Reputation: 180

C++ Error when Initializing a pointer to a pointer

I am using a large code-base, so forgive me for not including all source code. I will summarize the problem as best I can and hopefully it is enough to give some intuition into an answer.

When creating a pointer to a pointer (used as a dynamic array of pointers), I get an error somewhere in the heap, see image below for call-stack:

Error

all setFrontNodes() is:

void Node::setFrontNodes(int size) {
    frontNodes = new Node*[size]; // ERROR ON THIS LINE
    nFrontNodes = size;
}

Where the header for my class Node is:

class Node {
public:
    ~Node();
    int nBackNodes;
    int nFrontNodes;
    Node** backNodes;
    Node** frontNodes;
    void setFrontNodes(int size);
    void setBackNodes(int size);
    double value;
    double valuePrime;
    ActivationFunction* activationFunction = NULL;
    InitWeightMethod* initWeightMethod = NULL;
    void initWeights(double multiplier);
    double bias;
    double deltaBias;
    double* weights;
    double* deltaWeights;
    double errorGradient;
    Node(int number);
    void forwardProp();
    int number;
    string label;
    int layer;
};

Now here is the strange issue. The error will happen randomly. I will run the same program with same parameters and everything, and the error will either happen there, or at another time while running, or not at all! This makes it extremely difficult to track the bug down and why I do not have a full code example that can be repeated.

It sounds like there is some issue allocating memory on the heap, though I am not sure what it could be or how to fix it. Vectors do not cause errors but are mind numbingly slow when training neural networks such as I am using the code for.

I ran memory diagnostics, and I still have over 4gb free of RAM when the error happens.

Thanks for any time! Let me know if you want anything else, but like I said it is a large program and the error appears random so I am looking for a general problem that I might be running into when allocating memory on the heap which is causing the ntdll.dll!_RtlReportCriticalFailure@12() error in the screenshot.

Upvotes: 0

Views: 446

Answers (1)

Alecto
Alecto

Reputation: 10740

As commented by Igor Tandetnik, this sort of error is likely due either to a garbage value for size, or due to the heap being corrupted. Make sure size is a valid number, and make sure that you're not writing to memory you're not supposed to touch (as this could corrupt the heap).

If possible, you can use a code sanitizer (like clang) to check for this, or you could use a tool like valgrind to see when it happens.

Upvotes: 1

Related Questions