Salem C was pretty low key in his answer; I think it's worth saying this a bit harder:
To avoid memory leaks, don't use new. Don't use delete. Don't do manual memory management. The order of preference is:
1) On the stack, not the heap.
2) If you MUST have it on the heap, create it with make_unique or make_shared, and use a unique_ptr or a shared_ptr to manage its lifetime.
3) If you really can't do that, go back and redesign your code so that you can.
4) When you've got enough experience and knowledge to know the cases when you really really must do it yourself, manually, you'll try really hard not to.
how would you prevent memory leak in this situation
1. By not using a Variable Length Array (VLAs).
2. By not using new, especially in a function.
I'd use one of the STL containers, such as a std::vector or std::array. Memory management is built in. When the container object goes out of scope, so does it's its used memory.