bar *foo;
foo = new bar [100];
foo = new bar [10];
Is this a memory leak?
Using the new operator on the same pointer twice, with a smaller number of elements the second time, like so:
I imagine so, as there is now no way to free the memory allocated by the first call. That's nothing to do with the size of memory you're getting, by the way.
Yes. You are not deleting after repositioning your ponter to the newly created memory block. Doesn't matter if it is a bigger or smaller number: the memory isn't reused when you do new unless you have deleted it.
So, I should delete the allocated memory before I resize it, then set it to NULL (or can I just new it again without setting it to NULL?).
And thanks for the snappy responses.
And thanks for the snappy responses.
You can just new it after a delete. You set it to NULL when you don't plan on reusing it, but wish to safeguard against accidentally trying to do so later on.
Quote:Original post by Anonymous Poster
It is faster to use malloc and realloc, then to delete and new.
Except for the whole not handling object constructors and destructors.
Quote:Original post by Anonymous Poster
It is faster to use malloc and realloc, then to delete and new.
But a very bad idea, for many reasons. Also for POD-types the performance is most likely the same and for non-POD types malloc and realloc wont work properly.
Malloc: allocates memory -- O(c)
New: allocates memory, calls constructor for every element -- O(n)
GCC (don't know if others compilers do this) has an awsome facility when it comes to allocating POD or non POD types.
It checks if the type is POD or not and, then, you get to call different functions by using a dummy argument: one function has __false_type (for non POD) and the other has __true_type (for POD).
You can do the same with deleting.
New: allocates memory, calls constructor for every element -- O(n)
GCC (don't know if others compilers do this) has an awsome facility when it comes to allocating POD or non POD types.
It checks if the type is POD or not and, then, you get to call different functions by using a dummy argument: one function has __false_type (for non POD) and the other has __true_type (for POD).
#include <bits/type_traits.h> // for __false_type and __true_type#include <stdlib.h> // for malloc#include <stdexcept> // for std::bad_alloc#define verif_POD_type(__type__) typename __type_traits<__type__>::is_POD_type()template <class Type>void __allocate_aux(Type *ptr, unsigned int size, __false_type) // isn't POD{ try { ptr = new Type[size]; } catch(std::bad_alloc ex) { // do error stuff }}template <class Type>void __allocate_aux(Type *ptr, unsigned int size, __true_type) // is POD{ ptr = (Type*)(malloc(sizeof(Type)*size)); if(!ptr) { // do error stuff }}template <class Type>inline void allocate(Type *ptr, unsigned int size){ __allocate_aux(ptr,size,verif_POD_type(Type));}
You can do the same with deleting.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement