I know you can make a dynamically sized array using malloc
, but I'm interested in doing the same thing using new
, partly because malloc
is considered bad practice in C++ and mostly out of curiosity.
Say I'm writing a program that will receive an input of bytes that could be as many as MAX_INPUT_SIZE
, which is so large that allocating an array of that size could potentially impede the ability of other programs to run on the same RAM. However, all input sizes [0, MAX_INPUT_SIZE]
are equally as likely to be received. Is there a way to write the program in such a way that memory allocation on the heap is proportional to the input size so that performance of other programs are not affected unless a large enough input is received? Assume these restrictions:
- Cannot use
malloc
- Cannot use
vector
or other wrappers (let's say we are looking for extremely fast performance) - The algorithm to interpret the data MUST have all data available in one array (for performance reasons, and so that small inputs will still be processed very fast)
- Program should allocate memory approximately equal to input size
These restrictions are unrealistically tight but it's just hypothetical. Here is a potential solution:
char *data;
long long int data_size;
/* receive input size */
if( data_size <= 1000 )
data = new char[1000];
else if( data_size <= 10000 )
data = new char[10000];
...
else if( data_size <= MAX_INPUT_SIZE / 10 )
data = new char[MAX_INPUT_SIZE / 10];
else if( data_size <= MAX_INPUT_SIZE )
data = new char[MAX_INPUT_SIZE];
My question is, does the above code actually only allocate new
memory when its line of code is run, or does it prepare memory for all those new
calls, and just assign the pointer to the one requested?
Essentially, would this program run on computer where MAX_INPUT_SIZE
exceeds the available RAM, but the actual data_size
does not?
If the answer is, yes it would run, then why does new
force you to have an array size that resolves at compile time? Surely it's possible for the C++ compiler could make new
allocate dynamically then? If so then is it simply a design choice, and what would be the reasons for disallowing dynamic array size allocation?
If the answer is, no it wouldn't run, is there an alternate solution given the restrictions?