I am allocating a dynamic array of size n with operator 'new', filling it with data and then I need to get an array with this data, but with a lesser size. If I were allocating memory with malloc, I could simply write
int* p = (int*)malloc(n*sizeof(int)); ... p=(int*)realloc(p, m*sizeof(int)); (m<n)
this code will neither cause copying of data nor memory leaks. However, if I use 'new' for allocating memory, it is impossible to use 'realloc'. Is there any other way?
P.S. I know about vectors and stuff like this, no need to write about them. The question emerged because of curiosity and will to learn how things work on the low level
Asked
Active
Viewed 32 times
0
Arsenicum
- 1
- 2
-
1Re: "this code will [not] cause copying of data" -- that's not guaranteed. `realloc` is required to shrink the block in place "if possible". Whether it's possible is up to the implementor. As to memory leaks, if, for whatever reason, the call to `realloc` fails, it returns a null pointer, so you have to hang on to the original pointer, just in case. `p = realloc(p...)` doesn't do that. – Pete Becker Nov 20 '21 at 16:38
-
"I ran some tests" is not the same as "the standard requires...". – Pete Becker Nov 21 '21 at 17:57