# SwapWith crashes my code

**URL:** <https://forum.juce.com/t/swapwith-crashes-my-code/54762>\
**Category:** General JUCE discussion\
**Created:** [January 28, 2023, 10:12pm UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762 "2023-01-28T22:12:33Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![loveslap](https://avatars.discourse-cdn.com/v4/letter/l/ecae2f/32.png) [@loveslap](https://forum.juce.com/u/loveslap)\
**Post date:** [January 28, 2023, 10:12pm UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/1 "2023-01-28T22:12:33Z")

</div>

Happens as soon as I play a note.

```auto
/*
  ==============================================================================

    MidiProcessor.h
    Created: 28 Jan 2023 11:48:25am
    Author: charles

  ==============================================================================
*/

#pragma once
#include "JuceHeader.h"

class MidiProcessor
{
    juce::int64 now;
    juce::int64 before=0;
    juce::int64 interval;
    std::list <int> chordlist;

    
    
    public:
    
    
    int noteoncount[128] = {0};
        void process(juce::MidiBuffer& midiMessages)
    {
            juce::MidiBuffer::Iterator it(midiMessages);
            juce::MidiMessage currentMessage;
            int samplePos;
            int transposition;
            juce::MidiBuffer processedBuffer;
           
            
            while (it.getNextEvent(currentMessage,samplePos))
            {

                if (currentMessage.isNoteOnOrOff()) {
                    currentMessage.setChannel(4);
                    currentMessage.setNoteNumber(44);
                    processedBuffer.clear();
                    processedBuffer.addEvent(currentMessage, samplePos);

                    midiMessages.swapWith(processedBuffer);

                    }
                
            }
            
            
    }
   
};

```

---

<div class="post-metadata">

**Author:** ![Rincewind](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/rincewind/32/10645_2.png) [@Rincewind](https://forum.juce.com/u/Rincewind)\
**Post date:** [January 29, 2023, 12:09am UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/2 "2023-01-29T00:09:20Z")

</div>

SwapWith doesn’t copy any data but just swaps the pointer to the memory location. That’s a problem for the caller of process, because processBuffer is allocated on the stack and Is destroyed when it goes out of scope

---

<div class="post-metadata">

**Author:** ![loveslap](https://avatars.discourse-cdn.com/v4/letter/l/ecae2f/32.png) [@loveslap](https://forum.juce.com/u/loveslap)\
**Post date:** [January 29, 2023, 8:17am UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/4 "2023-01-29T08:17:49Z")

</div>

processedBuffer should be a global?

---

<div class="post-metadata">

**Author:** ![Rincewind](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/rincewind/32/10645_2.png) [@Rincewind](https://forum.juce.com/u/Rincewind)\
**Post date:** [January 29, 2023, 8:46am UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/5 "2023-01-29T08:46:49Z")

</div>

global variables are never a good solution in my opinion. I can’t really recommend any change without having more context about the code or what it is you are trying to accomplish

---

<div class="post-metadata">

**Author:** ![loveslap](https://avatars.discourse-cdn.com/v4/letter/l/ecae2f/32.png) [@loveslap](https://forum.juce.com/u/loveslap)\
**Post date:** [January 29, 2023, 9:32am UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/6 "2023-01-29T09:32:08Z")

</div>

# Context is that I’m trying to modify midi as it passed through the plugin

My code comes from

[![](https://us1.discourse-cdn.com/flex026/uploads/juce/original/2X/9/9ec836b7694ce6e8223dd372d0f7a98598795356.jpeg "Juce Tutorial 60 - Create your first MIDI Plug-in with Eyal Amir (Xfer Records)") ](https://www.youtube.com/watch?v=tgf6J8foCiw&t=1940s)

# Juce Tutorial 60 - Create your first MIDI Plug-in with Eyal Amir (Xfer Records)

It is called here (in PluginProcessor.c):

```auto
void NewProjectAudioProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages)
{
    juce::ScopedNoDenormals noDenormals;
    auto totalNumInputChannels = getTotalNumInputChannels();
    auto totalNumOutputChannels = getTotalNumOutputChannels();

    // In case we have more outputs than inputs, this code clears any output
    // channels that didn't contain input data, (because these aren't
    // guaranteed to be empty - they may contain garbage).
    // This is here to avoid people getting screaming feedback
    // when they first compile a plugin, but obviously you don't need to keep
    // this code if your algorithm always overwrites all the output channels.
    for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
        buffer.clear (i, 0, buffer.getNumSamples());
       theMidi.process(midiMessages);

    // This is the place where you'd normally do the guts of your plugin's
    // audio processing...
    // Make sure to reset the state if your inner loop is processing
    // the samples and the outer loop is handling the channels.
    // Alternatively, you can process the samples with the channels
    // interleaved by keeping the same state.
    for (int channel = 0; channel < totalNumInputChannels; ++channel)
    {
        auto* channelData = buffer.getWritePointer (channel);

        // ..do something to the data...
    }
}

```

---

<div class="post-metadata">

**Author:** ![Rincewind](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/rincewind/32/10645_2.png) [@Rincewind](https://forum.juce.com/u/Rincewind)\
**Post date:** [January 29, 2023, 9:34am UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/7 "2023-01-29T09:34:37Z")

</div>

The you should copy the MidiBuffer in your process method, clear it, iterate the copy, and add the modified MidiMessages back to the original (incoming) midiBuffer. I don’t think you should be using swapWith for that, it doesn’t create a deep copy as I previously stated.

---

<div class="post-metadata">

**Author:** ![loveslap](https://avatars.discourse-cdn.com/v4/letter/l/ecae2f/32.png) [@loveslap](https://forum.juce.com/u/loveslap)\
**Post date:** [January 29, 2023, 9:40am UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/8 "2023-01-29T09:40:31Z")

</div>

I want to _replace_ the midi messages with my modifications, how do I stop the original messages from passing through?

---

<div class="post-metadata">

**Author:** ![Rincewind](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/rincewind/32/10645_2.png) [@Rincewind](https://forum.juce.com/u/Rincewind)\
**Post date:** [January 29, 2023, 12:19pm UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/9 "2023-01-29T12:19:08Z")

</div>

You can clear the incoming midi buffer before you add your new message.

1. Copy incoming midi buffer
2. Clear incoming midi buffer
3. Iterate copied midi buffer  
3.1 Add modified midi message to incoming midi buffer

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [January 29, 2023, 12:58pm UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/10 "2023-01-29T12:58:27Z")

</div>

Maybe unrelated, but I don’t think the swapWith belongs inside the while loop

---

<div class="post-metadata">

**Author:** ![loveslap](https://avatars.discourse-cdn.com/v4/letter/l/ecae2f/32.png) [@loveslap](https://forum.juce.com/u/loveslap)\
**Post date:** [January 29, 2023, 1:42pm UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/11 "2023-01-29T13:42:37Z")

</div>

Why is that?

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [January 29, 2023, 3:40pm UTC](https://forum.juce.com/t/swapwith-crashes-my-code/54762/12 "2023-01-29T15:40:02Z")

</div>

Because the number of events is unknown. if it is more than one event you will swap the buffer back.

But the actual problem is, that the swap invalidates your iterator.

The iterator `it` iterates over the midiMessages. Inside the loop you pull the array under the bottom of the iterator away, so it points to thin air.

You should process the whole midiMessages filling the processedBuffer. When done you call swapWith once to replace the midiMessages with your processedBuffer.
