Using new in C++

Hi all.
Does new allocate extra space the size of what's in between [], or does it remove the previous space allocated and "resize" it to only the space between []? i.e. if you have char *newarray = NULL, and you put it in a loop of newarray = new char[1] that repeats 10 times, do you end up with 10 bytes of memory allocated for newarray, or one?
https://onplanners.com/invitations/wedding-suite
Last edited on
Does new allocate extra space the size of what's in between [],

That's up to the implementation, but using anything larger than the size is undefined behavior.

or does it remove the previous space allocated

What? new allocates memory, it doesn't "remove" anything.

and you put it in a loop of newarray = new char[1] that repeats 10 times, do you end up with 10 bytes of memory allocated for newarray, or one?

Without delete[] you would allocate 10 bytes with a memory leak of 9 bytes. In the end only 1 byte would be available to the array.

c++ is a hands-on language; it does not garbage collect** or attempt to make sure that you do not do things incorrectly when using low level features. New/delete are low level tools, and you have to be careful using them (and, most of the time, you do not need to use them at all).

** the operating system will GC when your program ends on most modern OS so small programs with small leaks are 'harmless' on most computers but still wrong and poorly coded.

every time new is called, there should be a delete called as well.
[1] is pointless, just say x = new thing;
you should not 'lose' or drop pointers.
int * x;
x = new int[10];
… //no delete, and no savng of x, but whatever other code
x = new int[5]; //the old x is lost. you can't recover that address, you overwrote it without saving it.

you can shuffle pointers:
x = new int[10];
int *y = x;
x = new int[5];
delete[] y; //the original x is deleted here, you had saved it. this kind of thing is done a lot in list/tree code.

Topic archived. No new replies allowed.