0

Generally when do you allocate memory in C++, you have new/delete and virtualalloc, amongst a few other API calls, is the generally for dynamic allocation, but then we have vector and such so what are the common uses for allocating memory?

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
user3333072
  • 139
  • 3
  • 4
    First of all you have to remember that C and C++ are two completely different languages. – Some programmer dude Mar 16 '14 at 15:49
  • Well if you don't need it, then you don't need it :) It's good to avoid new and delete when possible (it is almost always possible) – Niklas B. Mar 16 '14 at 15:49
  • removed the C tag because C doesn't have new, delete or vectors. If you intentionally wanted to ask about the situation compared in both languages, please reformulate the question – Niklas B. Mar 16 '14 at 15:50
  • Usually you don't do it directly, but let classes such as `std::vector` take care of it safely behind the scenes. – juanchopanza Mar 16 '14 at 15:54
  • Related, possibly duplicate: http://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself. – corazza Mar 16 '14 at 15:55

3 Answers3

2

If you don't know, at compilation time, how many items you will need, your best option is to use dynamic allocation.

That way you can (hopefully) deal with all the input without wasting memory by reserving an humongous space with a big array.

// ...
int humongous[10000]; // I only expect 10 items, so this should be enough for creative users
// ...
pmg
  • 106,608
  • 13
  • 126
  • 198
1

If you want to deal with large memory (i.e memory that can't be allocated on stack) then you can use dynamic allocation.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

As a general answer: "there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete."

source: http://www.cplusplus.com/doc/tutorial/dynamic/

b_mcq
  • 26
  • 3