Skip pointer to first packet between methods (Obj-C)

Something is missing for me, but I do not know how to fix it. The first version of this work:

- (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 DRY, I'm trying to make a method from creating a list of packages:

 - (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 EXC_BAD_ACCESS. Using GDB, packetList still looks good even inside sendPacketList ...

Looking at the documents , it seems that the thing I'm looking at is just a pointer to the first package in the list. So ... how can I do this?

0
source share
1 answer

The problem is that Byte packetBuffer[size+100] declares a local array that should not be accessed after this method completes. You have two options (which I will 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 will need a free() buffer later, which is a little painful.

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 will have to declare Byte packetBuffer[size + 100] outside the function and pass it as the first argument, which is also somewhat inconvenient.

+2
source

Source: https://habr.com/ru/post/1389559/


All Articles