Heap Corruption? Member variable value changing before processBlock is called [SOLVED]

Hi I’m fairly new to JUCE and I’m having issues with what I am suspecting to be a case of heap corruption (not entirely sure though). Basically, I have a member variable in my AudioProcessor class that is a struct, and it’s values seem to be changing wildly between when they’re initialized in the constructor and when processBlock is called.

Here is my struct (rtse is a library I’m using)

struct Context
{
    rtse::Context *rtse_context;
    float *input_spectrum;
    float *mask;
};

Here is my member variable

    Context context;

and here is my AudioProcessor constructor where values are assigned

    RtseProcessor()
        : AudioProcessor (BusesProperties().withInput  ("Input",  AudioChannelSet::stereo())
                                           .withOutput ("Output", AudioChannelSet::stereo()))
    {
        rtse::Context rtse_context(LICENSE_KEY);

        std::vector<float> input_spectrum(rtse_context.spectrum_size * 2);
        std::vector<float> mask(rtse_context.spectrum_size * 2);

        context.rtse_context = &rtse_context;
        context.input_spectrum = input_spectrum.data();
        context.mask = mask.data();
    }

rtse_context is initialized with its own member variables frame_size, buffer_size, and spectrum_size, which are initialized to 128, 512, 257 each. Here’s what the values look like at the end of the constructor.

Now, once processBlock is first called, however, these values are all messed up.


As you can see, the values are suddenly astronomical. I was curious what was happening so I chose frame_size and used Xcode’s “watch variable” functionality to see what was happening to it post-construction. I found out that the value was being changed in places like juce_HeapBlock.h, juce_ArrayBase.h, juce_AudioChannelSet.h, etc… Here are screenshots of the value changing


Has anyone experienced something like this before / does anyone have an idea as to why this might be happening? Thank you very much for your help.

You’re taking pointers to locals. Locals are destroyed at the end of their scope. When you read through the pointers in processBlock, they’re dangling already -there’s something else there now.

1 Like

Wow you’re right, thank you so much! I’m also fairly new to C++ so I’m getting used to the idea of pointers and whatnot. Thanks for your advice, it’s working now.

1 Like

The best advice I ever got about pointers was: don’t use them!

Why does your Context struct store pointers to all its data, instead of just storing its data?

If you write it like this:

struct Context
{
    rtse::Context rtse_context;
    std::vector<float> input_spectrum;
    std::vector<float> mask;
};

it will be much easier to avoid memory leaks and the millions of other bugs and issues that come with using raw pointers.