clGetDeviceIDs question

I’m trying to build an academic code that will basically operate on any system it’s loaded onto without uniformity (Giant red flag in this sentence eh?). For example a system with 1 platform and 4 devices or 1 platform with 16 devices, without modifying the code.

In any case, I’m getting pointers from the clGetDeviceIDs call, and then trying to return it from the function, which is a HUGE memory management issue because there are leaks everywhere. Case in point, this is how I had to work it to get the code to compile without warnings:

cl_device_id create_device(){

    cl_platform_id* platforms;
    cl_device_id* devices;
    int i, j;
    cl_uint platformCounter;
    cl_uint deviceCounter;
    cl_device_id dev;

    clGetPlatformIDs(0, NULL, &platformCounter);
    if(platformCounter<0){
        printf("Could not find any device on system");
        exit(1);
    }
    platforms = (cl_platform_id*)malloc(sizeof(cl_platform_id)*platformCounter);
    clGetPlatformIDs(platformCounter, platforms, NULL);

    for(i=0; i < platformCounter; i++){
        clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, 0, NULL, &deviceCounter);
        if(deviceCounter<0){
            printf("Model of device could not be discovered");
            exit(1);
        }
        devices = (cl_device_id*)malloc(sizeof(cl_device_id)*deviceCounter);
        clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, deviceCounter, devices, NULL);
    //cast devices as cl_device_id pointer to get the function to return what it is expecting        
    dev=(cl_device_id)&devices;
    }
    free(platforms);
    return dev;
}

To point out what I’m doing at the behest of many a c programmer:

cl_device_id create_device(){

    clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, deviceCounter, devices, NULL);

    dev=(cl_device_id)&devices;

    return dev;
}

I know this is incorrect and can be done inside the program instead of inside a function call. My question is this; the third argument of clGetDeviceIDs takes a numerical which is pointed to by the fourth argument. When putting in a number like 1 instead of deviceCounter, how does that work? Is the system only calling the first device it finds under that platform? Or is it calling the first available device, meaning that if set to 1 and the device was doing something it would then move onto the next device?

Sorry I am new to OpenCL and brushing up some old c knowledge, my end goal is to find out how many devices are on any system this is loaded onto. I appreciate any time you spent looking at this and any knowledge you send my way!

Edit: I understand how this works now, and this cannot be done in a function call, no need for any replies. What I was doing is impossible in C.