سؤال

I'm learning how to communicate with USB devices with IOKit, and I wrote this piece of code:

// Global variable
char *dataBuffer;

- (void)startPolling {
  if (!shouldPoll) { // Prevent polling twice
    shouldPoll = YES;
    timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(poll) userInfo:nil repeats:NO];
    [self performSelectorInBackground:@selector(poll) withObject:nil];
  }
}

- (void)poll {
  dataBuffer = (char *)malloc(numBytes);
  numBytes = 64;

  returnCode = (*usbInterface)->ReadPipe(usbInterface, 2, dataBuffer, &numBytes);
  // Handle received data in dataBuffer

  free(dataBuffer);
  [timer fire];
}

It works like this: another part of the code that works fine looks for the device, opens it, and then opens the correct interface. After that, when the user presses a button, it will call startPolling, which will set a timer that triggers the method poll every 0.5 seconds (sorta, the timer will fire again repeatedly).

In the poll method, the program will read the USB pipe and store data on dataBuffer. At first, I thought that I could alloc its memory once and reuse the pointer at every iteration, but for reasons I'm unfamiliar, the second ReadPipe call would fail. Always.

In an act of desperation, I came up with this (terrible?) idea: allocate and free the buffer memory at every iteration. For my surprise it did work, and I was able to read the device successfully.

The problem is that from time to time the program crashes with the error:

malloc: *** error for object 0x610000005890: Heap corruption detected, free list canary is damaged
*** set a breakpoint in malloc_error_break to debug

I really don't know what that means, let alone how to solve it. I set the buffer size to 64 to make sure that any data read would fit in the memory. Actual data is 18 bytes long.

Any clues?

هل كانت مفيدة؟

المحلول

These two statements should be the other way around:

dataBuffer = (char *)malloc(numBytes); 
numBytes = 64;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top