memory leak in code snippet?

Is there a memory leak in this code snippet with ptr being reassigned to another address &x to &y?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int x = 5;
    int y = 7;
 
    int *ptr = &x;
    std::cout << *ptr;
    *ptr = 6;
    std::cout << *ptr;
    ptr = &y;
    std::cout << *ptr;
 
    return 0;
}
> Is there a memory leak?

No. The objects involved ('x', 'y' and 'ptr') have automatic storage duration.

. automatic storage duration. The object is allocated at the beginning of the enclosing code block and deallocated at the end. - http://en.cppreference.com/w/cpp/language/storage_duration
The link was very helpful. For example's sake is it possible to create a memory leak above by adding to or modifying that code? Or does the automatic storage deletion take care of all of it?
You can create a memory leak by allocating memory on the heap using the new And then not deleting it. Memory allocated on the heap are not automatically removed like the one's created on the stack, which they are in your code.

http://www.cplusplus.com/doc/tutorial/dynamic/
Thx for clarifying.
Last edited on
Topic archived. No new replies allowed.