When to allocate memory dynamically?

2

In C ++ you can easily declare an object or variable like this:

tipo_da_variável nome_da_variável;

This type of declaration is the easiest to use, but you can also use new to allocate memory dynamically and then deallocate with delete.

Is it true that dynamically allocating objects leaves the program faster, ie does it take up less memory and CPU?

Should I always dynamically allocate objects?

If the answer to these 2 questions is no, then could you exemplify some cases where the use of dynamically allocated memory is justifiable? Or explain to me the usefulness of dynamically allocating memory?

I've heard that allocating memory dynamically is something that should be done when we do not know how much memory we'll need, but I also did not understand this argument right, after all my compiler accepts without error the code:

int num1;
cin >> num1;
char palavra[num1];

In the code above, the size of the array will depend on the value that the user type, that is, the start, we do not know how much memory the program will use and even then, required new + delete

    
asked by anonymous 17.04.2018 / 16:41

1 answer

3
  

variable_type variable_name;

     

This type of declaration is the easiest to use

Yes, but it is wrong. Not initializing a value is an error.

This form is called automatic allocation.

  

It's true that dynamically allocating objects leaves the program faster

No, in general the opposite, you should avoid dynamic allocation as much as possible, without causing other problems.

  

Does it take up less memory and CPU?

These are different things, but dynamic allocation will invariably consume more memory. Work to allocate is often monumental compared to automatic allocation. And if it is not, the release will be monumental. You can not categorically state why C and C ++ let you manage memory in different ways.

  

Should I always dynamically allocate objects?

No, it's much more complicated to manage this.

  

Could it possibly exemplify some cases that the use of dynamically allocated memory is justifiable?

I think this is already answered in several questions:

  

After all, my compiler accepts the code without error

Running is different from being right.

  

Inthecodeabove,thesizeoftheArraywilldependonthevaluethattheusertype,ie,thestart,wedonotknowhowmuchmemorytheprogramwilluseandanyway

Noproblem,youcandoautomaticallocationsetatruntime,thisdoesnotmaketheallocationdynamic.

17.04.2018 / 17:30