Clip detection crashes Live

I’m adding automatic clip creation to a Max for Live device I created which records MIDI notes automatically so if you forgot to press record, the last take can instantly be recalled to a clip. Previously a user had to create a clip before placing the notes into the clip. I’m working on the ability for the device to create a clip and place the notes inside the new clip in a single step. So far that has worked flawlessly. The problem I’m running into is likely with my error checking.

When triggered, the device will check which clip slot is selected, create a clip then add the notes into the new clip. Before doing so I’m checking to see if a clip already exists in the selected slot. If there is a clip in the selected clip slot I increment to the next slot and check for a clip in the new slot. The process continues until an empty slot is detected. This is when trouble starts.

When I detect there is a clip in the selected slot, Live unexpectedly quits. I’ve added breakpoints to the subpatch which does the clip detection and data is flowing exactly how I’d like it to so I’m pretty confident the error checking is sound. Thinking perhaps the numbers representing the track and clip were floats rather than ints I tried incrementing with both and it crashes the same. Before trying an entirely different approach to the problem I thought I’d see if anyone has ideas.

Here is the sub patch which does the clip detection. Does anyone have thoughts or a suggestion?

— Pasted Max Patch, click to expand. —

Copy all of the following text. Then, in Max, select New From Clipboard.

I figured out what was going on. Previously the device had been working because the user had to manually create a clip. After the user created an empty clip they would click a bang button in the device which would call replace_selected_notes to add notes to the empty clip. Everything was good.

In my update I added the create_clip call to create a clip so the user wouldn’t have to. When I detected a clip in the selected slot I would move on to the next slot until an empty one was found. The plan was to create a clip and add notes. However, when I called replace_selected_notes on a clip that wasn’t selected, Live would crash. Since there were no notes in the clip previously it never occurred to me to make a call to select_all_notes. As long as I call that before replace_selected_notes on an empty clip that isn’t selected, everything works just fine.

In the end I learned I should select notes before replacing them and that replace_selected_notes can crash Live if no notes are selected. Here is a sample patch if anyone wants to try crashing Live for themselves.

— Pasted Max Patch, click to expand. —

Copy all of the following text. Then, in Max, select New From Clipboard.