Bloomberg LP Interview Question
Financial Software Developersstatic variables are stored in data segment while new operator in heap.
The static user-defined variable creation doesn't automatically initialise it while new operator calls a default constructor for initialisation.
static variables memory is freed at program exit but memory allocated through new should be deallocated before you exit as better practise and to avoid memory leaks.
>The static user-defined variable creation doesn't automatically initialise it while > new operator calls a default constructor for initialisation.
Each static variable must be *defined* in exactly one compilation unit. It can be initialized at the point where it is defined. Else the compiler null initializes it. If the variable is a user defined type, the (default)constructor will be called before the main() execution begins.
Here is an illustration how the program crashes trying to delete statically created object:
void InsertLeadingDigitIntoArray(int*& Arr, int& n)
{
Arr[Index]=0;
int* Arr2;
Arr2 = new int[n+1];
Arr2[0] = 1;
memcpy(&Arr2[1], &Arr[0], n*sizeof(int));
delete [] Arr; // BANG! Here it crashes! - trying to delete dynamically (from the heap)
Arr = Arr2;
n++;
}
// inside main:
int Array[]={4,5,6,7,8,7,6,5,4,3,2}; // statically allocated (in the stack)
int* Arr=&Array[0];
int n;
n=sizeof(Arrray)/sizeof(int);
InsertLeadingDigitIntoArray(Arr, n);
haha seriously?
- Anonymous August 20, 2010