int * function(int)

Hello everyone!

I've working with vectors for ever but lately I've gone back to working with dynamic arrays. I remember I used to do some tricks (which obviously I have learned) so I can have a function return multiple values of the same data type.

Now I want to trace what physically happens in memory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int * funct(int m)
{
    int * p = new int[2];  // allocate space for two ints on the stack
    *p     = m+m;
    *(p+1) = m*m;

    return p;             // return the address of p
}

int main()
{
    int * ptr = funct(10);
    cout << *ptr << " " << *(ptr+1) << endl;   // retrieve the values of ints
    return 0;                                  // stored at p and p+1
}



Now I uncomfortable because I didn't free the memory, I know the memory occupied by p is destroyed when function() returns but not the memory p points to.

NOTE: I am actually using C so I'm using malloc and c-streams instead of new and c++ streams respectively and I don't know why I didn't write the code in C! :D

What am I getting wrong here?

Last edited on
What am I getting wrong here?


I'm not sure what you mean by this.

You are correct that the memory is never free'd and that you should do it before you program exits.

Also:

1
2
3
cout << *ptr << " " << *(ptr+1) << endl;
//can be written as
cout << ptr[0] << " " << ptr[1] << endl;
Last edited on
1
2
3
cout << *ptr << " " << *(ptr+1) << endl;
//can be written as
cout << ptr[0] << " " << ptr[1] << endl;


Thanks for clearing that out, but I prefer writing it in this way because sometimes I only write *(ptr++) (I know this increments the pointer and I must decrement it sometime later).

What I mean:

I didn't free(p) in funct(), and I couldn't because I'd lose the data, obviously. So with bigger arrays, I would have memory leakage, no?
Thanks for clearing that out, but I prefer writing it in this way because sometimes I only write *(ptr++) (I know this increments the pointer and I must decrement it sometime later).


Well if you are trying to use the data as an array I would suggest you use the array notation if only because it is easier to read.

Yes, you would have a memory leak if you never free'd it.

Note that the point of the dynamic memory is that it will outlive that scope, so you can free it later if you need to, as long as you still have a pointer to the data.

Since you still have the pointer in main, just free it before you exit main and you will have prevented the memory leak.
Ahh, I was just about to ask how do I go about freeing it, one problem: do I free it element wise i.e.

delete ptr; delete (ptr+1) or is delete [] ptr;? In the latter case, how would the compiler know that the size of the dynamically allocated space is that of 2 ints? I mean we are deleting that space by using the delete operator not on p itself inside funct(), but rather on ptr, which is in main().
Topic archived. No new replies allowed.