Question

I'm missing something here, but I'm not sure how to fix it. The first version of this works:

- (void) sendBytes:(const UInt8*)bytes size:(UInt32)size
{
    Byte packetBuffer[size+100];
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, sizeof(packetBuffer), packet, 0, size, bytes);
    [self sendPacketList:packetList];
}

For DRYness, I try to make a method out of the packet list creation:

- (MIDIPacketList*) makePacketList:(const UInt8*)data size:(UInt32)size
{
    Byte packetBuffer[size+100];
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, sizeof(packetBuffer), packet, 0, size, data);
    return packetList;
}


- (void) sendBytes:(const UInt8*)bytes size:(UInt32)size
{
    MIDIPacketList *packetList = [self makePacketList:bytes size:size];
    [self sendPacketList:packetList];
}

And now the sendPacketList method fails with an EXC_BAD_ACCESS. Using GDB, the packetList still looks good even within sendPacketList...

Looking at the docs, it seems that the thing I'm passing around is just a pointer to the first packet in the list. So... how can I do this?

Was it helpful?

Solution

The trouble is that Byte packetBuffer[size+100] declares a local array, which must not be accessed after that method exits. You have two options (which I'll write as functions):

Option 1:

MIDIPacketList *makePacketList(const UInt8 *data, UInt32 size) {
    Byte *packetBuffer = malloc(size + 100);
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, sizeof(packetBuffer), packet, 0, size, data);
    return packetList;
}

If you do it this way, you'll have to free() the buffer later on, which is kind of a pain.

Option 2:

MIDIPacketList *makePacketList(Byte *packetBuffer, const UInt8 *data, UInt32 size) {
    MIDIPacketList *packetList = (MIDIPacketList*)packetBuffer;
    MIDIPacket     *packet     = MIDIPacketListInit(packetList);
    MIDIPacketListAdd(packetList, size + 100, packet, 0, size, data);
    return packetList;
}

In this case, you'll have to declare the Byte packetBuffer[size + 100] outside of the function and pass it in as the first argument, which is also somewhat inconvenient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top