One of my colleagues declared, and initialized, a global variable using new:
#define MAX_SIZE_TABLES (1024 * 1024)
unsigned char * ImageBuf = new unsigned char[MAX_SIZE_TABLES];
The code compiles and builds with no errors using Microsoft Visual Studio 2010 Premium.
My questions:
Is this legal by the standard or undefined behavior?
When is memory deleted if no function calls delete?
Edit 1: added "initialized" after "declared for variables".
new does not declare variables. It allocates memory. The declaration part is this:
unsigned char * ImageBuf
The:
= new unsigned char[MAX_SIZE_TABLES];
part, is the initialization, not the declaration.
It is legal to initialize variables in-place at global scope, including using new or a function call. The memory is not freed automatically by the program (manually allocated memory is never freed automatically; it doesn't matter where the allocation happens.) When the process exits, memory is freed by the operating system (along with all the usual clean-up, like closing files, etc.) But of course this is platform-specific. From the point of view of the program, memory is never freed during its lifetime.
It is legal but definitely not recommended. It is a global variable. The memory will be released when the process terminates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With