Declaring a cl_uint variable in OpenCL C leads to Segmentation fault (core dumped)

125 views Asked by At

I have written a code in OpenCL C to list all the available platforms.

int main()
{
    cl_context context;
    cl_platform_id* platforms;
    cl_device_id* devices;
    cl_uint platformcount;
    cl_int ret;
    clGetPlatformIDs(2,NULL,&platformcount);
    clGetPlatformIDs(platformcount,platforms,NULL);
    /*if(ret==CL_SUCCESS)
    {
        printf("\nNumber of platforms found=%d\n",platformcount);
    }*/
    return 0;
}

This leads to the core being dumped (Segmentation fault (core dumped)).

$ gcc -lOpenCL a.c -o a && ./a
Segmentation fault (core dumped)

However, if I comment out the ret declaration the code compiles fine.

int main()
{
    cl_context context;
    cl_platform_id* platforms;
    cl_device_id* devices;
    cl_uint platformcount;
    //cl_int ret;
    clGetPlatformIDs(2,NULL,&platformcount);
    clGetPlatformIDs(platformcount,platforms,NULL);
    /*if(ret==CL_SUCCESS)
    {
        printf("\nNumber of platforms found=%d\n",platformcount);
    }*/
    return 0;
}

Why does this happen?

1

There are 1 answers

4
alk On BEST ANSWER

This call

clGetPlatformIDs(platformcount,platforms,NULL);

writes to where platforms points to, but platforms had not been initialised to point anywhere, thus the call invokes UB.