简体   繁体   中英

How can I free any dynamic memory allocated inside a function?

I'm working on a problem and I've been asked to create a function that returns a pointer. The program I wrote works fine and all; however, I create dynamic memory allocation inside my function called *newArray and I don't think I'm freeing that allocated memory the pointer ptr2 is pointing to inside this function. Is there a way to release this memory?

I was thinking of adding another parameter to the function - the ptr2 pointer from the main function - and just alter that pointer inside the function, but that defeats the purpose of the function returning a pointer. Any thoughts here?

Here's my code:

//Problem #12
#include <iostream>
using namespace std;

void SizeEntry(int*);
void DataEntry(int*, int);
void ShowArray(int *, int);
int *newArray(int *, int);

int main()
{
    int size, new_size;
    int *ptr=nullptr, *ptr2 = nullptr;

    //grab size and dynamically allocate an array to the entered size
    SizeEntry(&size);
    ptr = new int[size];

    //make size of second array
    new_size=size+1;

    //Fill array with data and make a new copy w/ requirements
    DataEntry(ptr, size);
    ptr2 = newArray(ptr, size);

    cout<<"\nHere is the first array: \n";
    ShowArray(ptr, size);
    cout<<"Here is the new array: \n";
    ShowArray(ptr2, new_size);

    //free allocated array
    delete [] ptr;
    delete [] ptr2;
    ptr = nullptr;
    ptr2 = nullptr;

    return 0;
}
void SizeEntry(int *size)
{
    cout<<"Enter the size of your list: ";
    cin>>*size;
    while(*size<0)
    {
        cout<<"Size must be non-negative, enter another number: ";
        cin>>*size;
    }
}
void DataEntry(int *ptr, int size)
{
    for(int count = 0; count<size; count++)
    {
        cout<<"Enter data for entry #"<<(count+1)<<": ";
        cin>>*(ptr+count);
        while(*(ptr+count)<0)
        {
            cout<<"Data point cannot be negative, try again: ";
            cin>>*(ptr + count);
        }
    }
}
void ShowArray(int *ptr, int size)
{
    for(int count=0; count<size; count++)
        cout<<*(ptr+count)<<" ";
    cout<<endl;
}
int *newArray(int *ptr, int size)
{
    int *ptr2=nullptr;
    int new_size = size+1;
    int counter=0;

    ptr2 = new int[new_size];

    for(int count=0; count<new_size; count++)
    {
        if(count==0)
            ptr2[count]=0;
        else
        {
            ptr2[count]=ptr[counter];
            counter++;
        }
    }        
    return ptr2;
}

You are freeing ptr2 in main. To this you assign prt2 of your function before with your return value. So both pointers are pointing to the same memory as this is the thought of pointers. When you free ptr2 in main, you automatically free ptr2 in your function because they are the same --> see your assignment. So from my point of view there is now problem with allocated memory.

Come on, I don't see any problem here. But I think it worth to tell you that, ptr2 in main function is assigned by the returned pointer of newArray function, and that main-ptr2 is logically identical to the newArray-ptr2.

When I say "logically", I mean of course they are to different pointers. Pointer is variable too, so main-ptr2 and newArray-ptr2 are two different pointers, they are stored in different places in the memory. HOWEVER, they have the same value, which is an address information of some other variable in the memory. Having the same value means they are pointing to the same memory block.

Me and my brother are two different people, I am pointing to a beautiful women and tell my brother "hey, look at that beautiful lay!", and now, my brother also pointing to that pretty lady.

So, two pointer, one target. If you try to release the target, using delete ptr2 in main, the target pointed by both main-ptr2 and newArray-ptr2 will be destroy.

BTW, newArray-ptr2 actually no longer exists, because it is an auto variable of newArray function.

Think in terms of low-level memory details. Inside the newArray function you are allocating a memory chunk through new and assigning the base-address of that chunk to ptr2 pointer.

You, then return the ptr2 pointer from the newArray function and assign that pointer to the ptr2 pointer inside of main() .

Ultimately, you free the memory chunk held by you through the delete statement, wherein you tell the machine to free the contiguously-allocated memory chunk pointed by ptr2 .

I do not see any reason for any memory leak. For better understanding, I would recommend running this program of yours through a debugger(gdb).

To Free the memory allocated by "new Operator" in C++, Just use delete operator and nothing else.

No need to assign null to the pointer whose memory is already freed by delete operator.

PS: IF YOU INTENDED TO USE THAT POINTER AGAIN, ONLY THEN ASSIGN IT TO NULL.

So in your case the last two line of code are useless unless you are intended to use that pointer again.

 //free allocated array
    delete [] ptr; 
    delete [] ptr2;
    ptr = nullptr; //Useless as memory is already free assigned to ptr 
    ptr2 = nullptr;//Useless as memory is already free assigned to ptr2

In the *newArray function you are returning one pointer ie ptr2.

When you return ptr2 a copy of the value (an address) of ptr2 is made and returned to the caller. ptr2 was declared with automatic storage duration. It is the memory it refers to that must be freed and you are doing it in main as ptr2 of *newArray is assigned to ptr2 of main function.

PS :If you have any doubts debug it in Visual Studio you will get the clear Idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM