在 OpenCL C 中声明 cl_uint 变量会导致分段错误(核心已转储)

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

我用 OpenCL C 编写了一段代码来列出所有可用的平台。

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;
}

这导致核心被转储(Segmentation fault (core dumped))。

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

但是,如果我注释掉 ret 声明,代码可以正常编译。

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;
}

为什么会这样?

这次通话

clGetPlatformIDs(platformcount,platforms,NULL);

写入 platforms 指向的位置,但 platforms 尚未初始化指向任何位置,因此调用调用 UB。