Declaring & initializing variables with new, outside function scope
c++, global-variables, memory-management, new-operator, visual-studio-2010
Solution
`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.
Problem
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".