Is there a memory leak?

I have a c++ code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class example
{
public:
int div(int a, int b)
{
cout << a/b;
}
};

example * init()
{
example *a;
a = new example;
return a;
}

int main
{
example *k;
k = init();
k->div(5,7);
delete k;
}
No, there is no leak here.

The question is, though, why do you use new if you don't have to? The same thing can be accomplished more simply:

1
2
3
4
5
6
int main()
{
  example k; // no pointer
  k.div(5,7);
  // <- no need to delete because nothing was new'd
}

It is a pointer initialize example. I will use it. But someone said it has a memory leak and then i asked. It is just an example.
Thanks :)
@Disch:
a, declared on line 12 isn't being deleted (though it is made using new). Isn't that a memory leak?
it is deleted in main. Still leak?
OK! I was unable to understand how it wasn't a memory leak.After running it step by step through a debugger, I understood what is happening...
Pointers are confusing!!!
Well, there could be a memory leak if there was an exception between the new and the delete that would exit from main, but the OS would have freed it when the process is closed.
Generally, the memory leaks which are important are those in loops, that constently increase memory usage while the program is running. The leaks of one variable once in the program lifetime rarely have much effect (unless is one big allocation of memory of course)
Thanks. So there is no leak. I always handle exceptions. It was just an example.
Topic archived. No new replies allowed.