Question

I've got a very basic, bare minimum libusb example going, which compiles, but the output produced by the following application:

#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>

int main(void) {
    puts("Looking for USB devices...");

    libusb_device **devices;
    libusb_context *context = NULL;

    ssize_t device_count = 0;

    device_count = libusb_get_device_list(context, &devices);
    if(device_count < 0) {
        puts("Unable to retrieve USB device list!");
    }

    printf("%lu devices found\n", device_count);

    return EXIT_SUCCESS;
}

is as follows:

Looking for USB devices... 
Segmentation fault: 11

The failure occurs on line 13:

device_count = libusb_get_device_list(context, &devices);

I'm running the above on Mac OS X 10.9, and have libusb version 1.0.9 installed via Homebrew.

Any idea what could be the problem?

Was it helpful?

Solution

The code misses to initialise context.

Call libusb_init() prior to any operation on libusb.

Add a line like this before issueing any other call into libusb:

 int result = libusb_init(&context); 
 if (0 > result)
 {
   fprintf(stderr, "libusb_init() failed with %d.\n", result);
   exit(EXIT_FAILURE);
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top