Benifits of Dynamic Memory Allocation?

Started by
11 comments, last by garyfletcher 18 years, 9 months ago
In C++ when I allocate a long using malloc() just what are the benifits of doing this as apposed to just leaving it without its own specified space?
True God of the TribunalKelchargeMy SiteMy Ugly Forums
Advertisement
Really the only thing you'd be gaining by allocating a long dynamically is the obligation to delete it later.

The benefits of dynamic allocation is that it allows things to change at run-time. For example, the number of elements in an array.

It's also generally used for polymorphism, as you must have a pointer to do it properly (or at all AFAIK).

Dynamic allocation also tugs with it a slight performance bump, but one allocation of a long will by no means cause noticeably slower frame rates.
first off, in C++ your supposed to use new/delete to do allocations and deallocations!

and to answer your question, when you use this: long myLong; that will allocate myLong on the stack, when you do this: long *myLongPtr = new long; that will allocate myLongPtr on the heap.

the difference is that the stack is limited to the current scope and once the code leaves that scope, the variable is deallocated. When allocated on the heap the variable (or should we say variable memory) isnt deallocated until you do so using a delete call.

the heap is valid for the entire existence of your process, the stack is only around while you are inside the stacks acompanying scope.

use the heap and stack wisely!

EDIT: it should also be noted that the stack is much smaller than the heap, so when you're allocating a few huny-thousand variables, you'll probably corrupt the stack... heap to the rescue!
"I am a donut! Ask not how many tris/batch, but rather how many batches/frame!" -- Matthias Wloka & Richard Huddy, (GDC, DirectX 9 Performance)

http://www.silvermace.com/ -- My personal website
First off, malloc is C. In C++, you should always use new.

The main benefit of dynamically allocating something is that you can allocate space depending on runtime factors. Here's an example

#include <iostream>int main() {  int howManyFoos;  Foo* foos;  std::cout << "How many foos would you like to allocate space for ?";  std::cin >> howManyFoos;  foos = new Foo[howManyFoos];  std::cout << "Space for " << howManyFoos << "foos has been allocated.}


Edit: You guys are way too fast.
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Ok, so lets say I were to allocate a long by: long *mylongPtr = new long;
how would I do this for multiple long's. In the tutorial I am reading it says to do:
long *LArray;LArray = (long *)malloc(20); //which would allocate for 5 long's


How can this be duplicated using new/delete?
True God of the TribunalKelchargeMy SiteMy Ugly Forums
Whatever tutorial you are reading, if it's claiming to teach you C++, I would strongly advise you to stop reading it now.

Back to the question

long * LArray = new long[5];

// stuff

delete [] LArray;


Though in C++, you should probably be using a std::vector or other container rather than managing dynamic arrays directly.
Quote:Original post by kelcharge
Ok, so lets say I were to allocate a long by: long *mylongPtr = new long;
how would I do this for multiple long's. In the tutorial I am reading it says to do:
long *LArray;LArray = (long *)malloc(20); //which would allocate for 5 long's


How can this be duplicated using new/delete?


Stop reading that tutorial right now. That is awful.

Somewhat proper in C (tough I'm rusty):

long *LArray;LArray = (long *)malloc(5*sizeof(long)); //which would allocate for 5 long's


In C++:

long *LArray;LArray = new long[5]; //which would allocate for 5 long's

Edit: Beaten to it again [headshake]
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Hmmmmmm....It is true that genrally in C++ new() is preferred to malloc to allocate heap memory but people here don't really know the context in which the tutorial example is working.

Using new() will initialize the newed variable using a constructor - default or otherwise - whereas malloc will simply assign uninialized memory on the heap.

The are other methods to allocated uninitialised memory provided by the C++ library using the allocator class, memory.h, which would be generally used if you are writing your own container classes.

Malloc, and it's associated partners in crime realloc and calloc, would possibly be prefrerred if you were overloading new() within a custom memory manager.

Although any tutorial that tries to allocate enough memory for 5 longs using

LArray = (long *)malloc(20);

looks a little dodgy.

Anyhow, that's my 2 pennies worth..:)
Gary.Goodbye, and thanks for all the fish.
Quote:Original post by garyfletcher
Using new() will initialize the newed variable using a constructor - default or otherwise - whereas malloc will simply assign uninialized memory on the heap.


unless you explicitly invoke operators new/delete.

Quote:Original post by garyfletcher
The are other methods to allocated uninitialised memory provided by the C++ library using the allocator class, memory.h, which would be generally used if you are writing your own container classes.


std::allocator typically uses global operators new/delete via explicit invocation for allocation/deallocation only, construction is typically handled by placement new and destruction is done by explicitly invoking the destructor.

Anyways the real equivalent of:

#include <memory>T* array = static_cast<T*>(std::malloc(sizeof(T) * N));std::uninitialized_fill_n(array, N, T(...));//...for(int i = 0; i < N; ++i)  // only neccessary for NON POD-types with non trivial destructors   array.~T();std::free(array);


would be:

#include <memory>T* array = static_cast<T*>(::operator new(sizeof(T) * N));std::uninitialized_fill_n(array, N, T(...));//...for(int i = 0; i < N; ++i)   array.~T(); // only neccessary for NON POD-types with non trivial destructors::operator delete(array);


That should only ever be done in really low level code, infact std::vector works similarly.

Anways doing

long* array = new long[N];delete[] array;


As long is a built-in primitive type and scalar POD-type, elements of the array will have indeterminate initial values meaning there is no initialization/default construction going on and built-in primitive types don't really have destructors, in which case its approximately equivalent to using malloc/free also.

@kelcharge in C++ in general use C++ style dynamic arrays std::vector/deque.

[Edited by - snk_kid on July 9, 2005 5:35:41 AM]
poor guy only asked what the benift of using malloc was and he gets a complete breakdown of C++. Despite the fact he never said he's programming in C++ probably coding C.

Anyway dynamic allocation using malloc, or new in c++, is good for declaring things when you don't know exactly how many of them you'll need when you are coding.

Oh and its handy for creating objects C++ too.

If you know you'll need a long array with 5 elements then just use standard declaration. ie long argh[5];

Dynamic memory allocation really comes into it's own with linked lists and binary trees. These are alternatives to arrays with much flexibilty well worth doing some research into them.

This topic is closed to new replies.

Advertisement