Correct use of Realloc

realloc returns a pointer to the resized buffer; this pointer value may be different from the original pointer value, so you need to save that return value somewhere. realloc may return NULL if the request cannot be satsified (in which case the original buffer is left in place). For that reason, you want to save … Read more

Why is there no reallocation functionality in C++ allocators?

From: http://www.sgi.com/tech/stl/alloc.html This is probably the most questionable design decision. It would have probably been a bit more useful to provide a version of reallocate that either changed the size of the existing object without copying or returned NULL. This would have made it directly useful for objects with copy constructors. It would also have … Read more

Does std::vector *have* to move objects when growing capacity? Or, can allocators “reallocate”?

When std::vector<T> runs out of capacity it has to allocate a new block. You have correctly covered the reasons. IMO it would make sense to augment the allocator interface. Two of us tried to for C++11 and we were unable to gain support for it: [1] [2] I became convinced that in order to make … Read more

What does malloc(0) return? [duplicate]

Others have answered how malloc(0) works. I will answer one of the questions that you asked that hasn’t been answered yet (I think). The question is about realloc(malloc(0), 0): What does malloc(0) return? Would the answer be same for realloc(malloc(0),0)? The standard says this about realloc(ptr, size): if ptr is NULL, it behaves like malloc(size), … Read more

Proper usage of realloc()

Just don’t call free() on your original ptr in the happy path. Essentially realloc() has done that for you. ptr = malloc(sizeof(int)); ptr1 = realloc(ptr, count * sizeof(int)); if (ptr1 == NULL) // reallocated pointer ptr1 { printf(“\nExiting!!”); free(ptr); exit(0); } else { ptr = ptr1; // the reallocation succeeded, we can overwrite our original … Read more

How do you ‘realloc’ in C++?

Use ::std::vector! Type* t = (Type*)malloc(sizeof(Type)*n) memset(t, 0, sizeof(Type)*m) becomes ::std::vector<Type> t(n, 0); Then t = (Type*)realloc(t, sizeof(Type) * n2); becomes t.resize(n2); If you want to pass pointer into function, instead of Foo(t) use Foo(&t[0]) It is absolutely correct C++ code, because vector is a smart C-array.

tech