Dynamic Memory

For my CompSci exam, I am required to identify and fix errors when using Dynamic Memory. Specifically I need to know understand Memory Leaks, Dangling References, and Aliasing.

Since I'm taking a make-up, all the course material has been taken off our course management system, and I'm just using the internet as my only source.

From what I understand, a memory leak occurs when you dynamically allocate memory, but you can't delete and re-allocate the memory.


1
2
3
4
5
void someFunction(){
     int x = 5; 
     int *ptr = new int;
     ptr = &x; 
}


In this case nothing is pointing to the dynamically memory and a memory leak occurs, right?

I'm not sure what the other two terms are, I have a feeling that they are specific types of memory leaks? I need to be able to identify them, and fix them .

Any help on this would be greatly appreciated.

Thanks!


EDIT: Also, any links to tutorials on linked lists would be extremely helpful.
Last edited on
Every course is different, there's no telling how these concepts were introduced and how were they related to dynamic memory.

From outside point of view:

Yes, if you lose your only copy of the pointer returned by new, you have a memory leak because the object became unreachable.

A dangling reference is a reference to an object that doesn't exist:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int& bad()
{
    int n;
    return n;
}

int main()
{
    int& r1 = bad(); // r1 is dangling

    int* p = new int;
    int& r2 = *p; // r2 is okay for now
    delete p; // r2 is now dangling
}

These references can exist, but accessing them is undefined behavior (anything can happen)

Aliasing is when you have two references (or two pointers) referring to the same object through two different types:

1
2
3
4
5
6
7
8
int main()
{
    int n;
    float& bad = reinterpret_cast<float&>(n);

    int* p = &n;
    float* also_bad = reinterpret_cast<float*>(p);
}

C++ (and C) allows only very few kinds of aliasing (e.g. you can alias anything to a char& or char*). The rest is just like dangling references - it can exist, but accessing the referenced/pointed object as the wrong type is undefined behavior.
Last edited on
Yes, this is what I have collected from my searching as well.

I appreciate this. I'm just trying to gather as many examples of this as I can. I have no clue what to expect. I wasn't in class....and I have no notes.

Don't get sick on finals week. Lesson learned :P


Thank you.
Topic archived. No new replies allowed.