memory leak in code snippet?

Feb 7, 2016 at 1:37am
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;
}
Feb 7, 2016 at 1:49am
> 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
Feb 7, 2016 at 5:19pm
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?
Feb 7, 2016 at 5:25pm
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/
Feb 7, 2016 at 5:40pm
Thx for clarifying.
Last edited on Feb 7, 2016 at 6:17pm
Topic archived. No new replies allowed.