Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring & initializing variables with new, outside function scope

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".

like image 238
Thomas Matthews Avatar asked Feb 27 '26 21:02

Thomas Matthews


2 Answers

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.

like image 97
Nikos C. Avatar answered Mar 01 '26 12:03

Nikos C.


It is legal but definitely not recommended. It is a global variable. The memory will be released when the process terminates.

like image 36
piokuc Avatar answered Mar 01 '26 12:03

piokuc