0
Heap allocation is not always safe?
Hi I have a doubt below: As heap size is too much compared to stack size, I had a code as below which allocate on heap and deallocate it. I was told that this code is not always a safe code and may result into the memory error. Is it true ? I believe heap should not throw bad alloc as each step is giving memory back to heap due to delete[]. So effective allocation is memory of one iteration only. https://sololearn.com/compiler-playground/cNUHkIf4Hsn9/?ref=app
1 ответ
+ 1
I have read that the compiler has the prerogative to allocate either on the stack or in heap memory. It depends on the size and maybe some other factors of performance.
In your specific code, I would expect that nothing would get allocated because the optimizer should recognize that the object is never used. The entire loop should get eliminated because the optimizer will find that that its net effect is null.
Is the code safe? I presume it is, unless it presents a problem should it crash with an unhandled exception due to failed allocation. If you have doubt, then add error trapping.