I MUST put initialization and destroy steps inside the loop. After a number of correct iterations , it crashes giving CL_OUT_OF_RESOURCES error and I am not able to understand why.
I believe I destroy all resources. Following is the code
I know where leaking is from (in initGpu), but I cannot figure out why this happens.
I mean, exactly which OpenCL function returns CL_OUT_OF_RESOURCES? Your initGpu() function calls seven or so different OpenCL functions, and each one could have a different reason for failing. You need to individually check the return codes for *every* OpenCL function or it'll be impossible to find out what's going wrong.
You need to check the return code of every single OpenCL function to see if there's some problem starting earlier. Also, how many loop iterations happen before it fails? There could just be a memory leak in the OpenCL driver that's exposed if you loop 10 million times.
I'd also suggest commenting out more and more of your code to see if it passes, starting from the middle of your loop. If you can create/release contexts OK with no other code present, maybe there's an interdependence with some other kernel or OpenCL resource that you're not deallocating properly.