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?
This call
writes to where
platforms
points to, butplatforms
had not been initialised to point anywhere, thus the call invokes UB.