4

I am kind of getting bogged down by the concept of memory management (all my previous programming languages doesn't need me to manage the memory). I'm not sure if creating a variable will consume memory if I don't destroy it later.

#include <math.h>
#include <iostream>
using namespace std;

double sumInfiniteSeries(double u1, double r){
 return u1 / (1 - r);
}

double sumInfiniteSeries(double u1, double r, bool printSteps){
 if (printSteps){
  double lastTotal;
  double total = 0.0;
  double sn = u1;
  for (int n=1;n<=1000;n++){
   lastTotal = total;
   total += sn;
   sn *= r;
   cout <<  "n = " << n << ": " << total << endl;
   if (fabs(lastTotal - total) < 0.000000000000001) return total;
  }
  return total;
 } else {
  return sumInfiniteSeries(u1, r);
 }
}

Do i need to "destroy" any variables in these 2 functions?

Edit: So when I create my own class and its instance would I need to start memory management?

Pwnna
  • 9,178
  • 21
  • 65
  • 91
  • Generally, if you don't call `new`, you don't have to worry about memory management. Unless you deal with poorly crafted libraries of course. – Matthieu M. Sep 14 '10 at 14:55
  • 2
    Do get [a book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) on C++. – GManNickG Sep 14 '10 at 15:40

8 Answers8

15

What memory management? You’re only using the stack here, no memory management needed.

Manual memory management comes into play when you fiddle with new and delete.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 11
    ...and you can write an awful lot of C++ code without ever using `new` and `delete` (or `malloc` and `free`). The easiest way to deal with C++ manual memory management is to just not use it unless you absolutely have to. – Kristopher Johnson Sep 14 '10 at 14:36
  • 10
    And you can avoid even more use of `new` and `delete` by using someone else's code that does it for you, e.g. the STL. – Brian Sep 14 '10 at 14:46
  • memory management is not only about allocations. It's also about good algorithms and structure choices. – Guillaume Lebourgeois Sep 14 '10 at 15:16
  • 2
    @Guillaume: Not when someone is talking about C++ memory management. We are speaking not of finding efficient structures, but of ensuring that all memory used by the application is *eventually* returned to the C Runtime/Operating System. – Billy ONeal Sep 14 '10 at 15:28
3

As long as you stay away from new and especially delete, there is nothing to worry about w.r.t. memory management in C++.

If you do encounter a situation where you need to manually allocate some memory with new, the best thing you can do is to immediately hand the responsibility for that memory over to a smart pointer class, like auto_ptr<T>, unique_ptr<T>, shared_ptr<T>, etc.. Assuming you use the one with the right semantics, they will ensure the memory gets released at just the right time.

Bart van Ingen Schenau
  • 15,488
  • 4
  • 32
  • 41
  • make that `unique_ptr` and `shared_ptr` and I'm with you. – rubenvb Sep 14 '10 at 15:04
  • @rubenvb: I have added unique_ptr and made it more clear that the list is not meant to be exhaustive. – Bart van Ingen Schenau Sep 14 '10 at 15:10
  • @rubenvb: `unique_ptr` is not possible in the current C++ standard (not just not standard, not **possible**), and therefore advice given at present time is probably something like `scoped_ptr`. – Billy ONeal Sep 14 '10 at 15:29
  • well, `shared_ptr` isn't either, last time I checked. And when using `auto_ptr`, you'll wish it was never invented :). – rubenvb Sep 14 '10 at 15:35
2

Read Scott Meyers Effective C++ to save yourself weeks of pain. This is the best $$ you will ever spend as a beginning C++ programmer. Especially, learn what RAII is.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • 4
    You meant to say *after* the OP read a beginners book? Starting C++ with EffC++ will scare anyone. (Though it's a great book after any beginners book.) – Martin Ba Sep 14 '10 at 15:13
  • I'm not a completely beginner. I would say I'm proficient at Python and JavaScript. – Pwnna Sep 14 '10 at 15:27
  • @iltimatebuster: Which has what to do with C++? "I'm very good at driving a car, therefore I can fly this plane." No. Get a [beginner book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start from nothing. – GManNickG Sep 14 '10 at 15:40
  • -1: How to answer a specific question with RTFM. Agreed, the answer is in there, but the real answer isn't much longer than yours – rubenvb Sep 14 '10 at 15:58
  • @rubenvb - the OP started with "I am kind of getting bogged down by the concept of memory management (all my previous programming languages doesn't need me to manage the memory).". I too floundered around when I first started C++ after working with other languages, until I understood how to write it better esp. smart pointers and RAII, and thought that a fast track to this info would be helpful to OP. Sometimes there is more to a question that its title. – Steve Townsend Sep 14 '10 at 16:05
1

When you declare a variable without allocation qualifiers, as you have, the compiler assumes you mean auto. An auto variable exists for the lifetime of the scope in which it is defined, and then goes away. This usually happens by (though not by fiat of the language itself) placing the storage location for those variables on the call stack. When the function completes, the memory used by those variables is reclaimed automatically when the call pops the stack frame for the function off the call stack.

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
0

You only need to destroy variables allocated in the heap (i.e. via either new or malloc call).

In your example you only have automatic variables so you can't destroy them manually.

Emiliano
  • 22,232
  • 11
  • 45
  • 59
0

The other answers are correct in that you won't have caused any memory leaks with this code. But for completeness, there are other ways to be wasteful with memory too. Like passing objects by value instead of by reference.

In your case here it's not a problem. You're passing doubles and booleans. On a typical machine, doubles are 8 bytes instead of the 4byte pointers required to pass by reference. Not too big of a deal unless you think this is going to be an extremely busy and concurrent function.

But if you were using larger objects (structures, classes, etc), you'd do well to pass const references instead of having the system create a new structure and invoke the copy constructor to populate it.

Marc
  • 2,593
  • 2
  • 18
  • 21
0

Your code is fine. Basic rule of C++ memory management is return what you got :). If you got some memory using new, return it back to the system with delete.

I understand where you are coming from. Here's my suggestion list to master memory management in C++:

  1. Learn to compare and contrast malloc/calloc/alloca/free with new/delete/new[]/delete[].
  2. Be confident about operator new/operator delete usage
  3. Understand placement new -- this in conjunction with 2 form the crux of user defined memory management.
  4. Google for the term RAII, learn about auto_ptr and scoped_ptr
  5. Learn to handle error conditions gracefully. For e.g. when new fails it's supposed to throw an exception of type std::bad_alloc.
  6. Look into Dougleas Lea's dlmalloc implementation (google it)

Also remember, for every new there must be a corresponding delete. Otherwise this is a case of memory "leak". Use prudence while calling new/delete -- too many of these calls will slow your program.

Finally, automatically managed programming languages including those that have garbage collection related API may not always be the best solution to your problem domain. Fine grained memory management does help in performance optimization if done properly.

Fanatic23
  • 3,378
  • 2
  • 28
  • 51
0

Take a look at:

7.9 — The stack and the heap

This also might be helpful:

Memory Management Reference - Frequently Asked Questions

Robert S. Barnes
  • 39,711
  • 30
  • 131
  • 179