CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Dec 2001
    Location
    Greece, Athens
    Posts
    1,015

    Memory Allocation

    Hi. Suppose u have the following function:

    Code:
    int *temp(int n){
      int i;
      int *array = new int[n];
         for (i=0;i<n;i++)
       array[i] = i;
      return array;
    }
    If i call the above function in main like this:
    Code:
    temp(1000000);
    4Mbytes of memory are allocated, even though the result of temp() is not returned to another pointer. Why? Can I "free" that memory?
    Thanx
    Theodore
    Personal Web Page (some audio segmentation tools): www.di.uoa.gr/~tyiannak

  2. #2
    Join Date
    Mar 2004
    Location
    Israel
    Posts
    638
    try the following command:
    new int[1000];

    new doesn't care what you are doing with the return pointer,
    it does what it suppose to do: allocate and return start memory address...

    if you don't keep the pointer to that allocation, you can't free it.
    **** **** **** **** **/**

  3. #3
    Join Date
    Dec 2001
    Location
    Greece, Athens
    Posts
    1,015
    Thanx guysl. What if I call that function in another function? Shouldn't all the memory allocated in a function been free after the funcion has finished?
    e.g.

    void newFunction()
    {
    temp(1000000);
    }
    Theodore
    Personal Web Page (some audio segmentation tools): www.di.uoa.gr/~tyiannak

  4. #4
    Join Date
    Mar 2004
    Location
    Israel
    Posts
    638
    not with memory allocated on the heap with new/malloc.
    stack objects get free on end of scope.
    dynamic allocated memory gets free by explicit delete/free.
    **** **** **** **** **/**

  5. #5
    Join Date
    Dec 2001
    Location
    Greece, Athens
    Posts
    1,015
    Originally posted by Guysl
    not with memory allocated on the heap with new/malloc.
    stack objects get free on end of scope.
    dynamic allocated memory gets free by explicit delete/free.
    I was afraid that...
    The problem is that I have some functions for signal processing like:
    fft(Array)
    abs(Array)
    xcorr(Array)

    where Array is a class I've defined. All of those functions return an object to Array. Also, I've overloaded some operators. So if I write:

    Code:
    Array A1;
    Array A2;
    ....
    ....
    A1 = fft(A2)/sum(A2);
    ....
    So fft(A2) returns an Array which is divided (by using the overloaded operator /) by sum(A2). The result is returned to A1 but fft(A2) (intermediate retult) is returned no-where, so as u told me can't be free...
    Thanx for your answers...
    Bye
    Theodore
    Personal Web Page (some audio segmentation tools): www.di.uoa.gr/~tyiannak

  6. #6
    Join Date
    Mar 2004
    Location
    Israel
    Posts
    638
    well, it seems that destructor, copy c'tor and operator=
    are essential in your case.
    Last edited by Guysl; April 26th, 2004 at 08:28 AM.
    **** **** **** **** **/**

  7. #7
    Join Date
    Jun 2003
    Location
    Gjøvik, Norway
    Posts
    204

    Re: Memory Allocation

    Why not use a std::vector?
    Code:
    std::vector<int> temp(int n){
      int i;
      std::vector<int> array(n);
         for (i=0;i<n;i++)
       array[i] = i;
      return array;
    }
    This way the returned array will be deallocated automatically if you don't do anything with it.

  8. #8
    Join Date
    Dec 2001
    Location
    Greece, Athens
    Posts
    1,015
    I've explained in another thread why I don't use vector class. I want some extra features and I want a class created by me, not overloaded or sth else. Anyway, the class's fields are:
    Code:
    private:
      double *data;
      int size;
    And the constructor is:
    Code:
    ArrayD::ArrayD()
    {
     // constructor 1:
     ArrayD::size = 0;
     ArrayD::data = NULL;
    }
    
    ArrayD::ArrayD(int size)
    {
     // constructor 2:
     ArrayD::size = size;
     ArrayD::data = new double[size];
    }
    
    ArrayD::ArrayD(int size,const double p[])
    {
     // constructor 3:
     int i;
     ArrayD::size = size;
     ArrayD::data = new double[size];
     for (i=0;i<ArrayD::size;i++)	
       ArrayD::data[i] = p[i];	
    }
    and the destructor:

    Code:
    ArrayD::~ArrayD()
    {		
      delete [] data;
    }
    Any suggestions on the above code? Should the destructor be different??
    Thanx...
    Theodore
    Personal Web Page (some audio segmentation tools): www.di.uoa.gr/~tyiannak

  9. #9
    Join Date
    Nov 2002
    Location
    Devon, UK
    Posts
    212
    First, I'd use initialisations instead of code body, e.g.
    Code:
    ArrayD::ArrayD()
    : size(0),
      data(NULL)
    {
    }
    // etc
    Although you won't notice it on consturctors of this size, it's good practice and for complex classes you might notice a performance gain.

    Also, I think you need to check that the array has been allocated in the destuctor before delete'ing it:
    Code:
    ArrayD::~ArrayD()
    {
        if (data)
            delete [] data;
    }
    Lastly, you don't need to specifiy the scope of your variables inside the class's body - so constructor 3 could become
    Code:
    ArrayD::ArrayD(int nSize, const double* pData)
    :   size(nSize),
        data(new double[nSize])
    {
        // constructor 3:
        if (data)
        {
            for (int i = 0; i < nSize; i++)	
                data[i] = pData[i];
        }
    }
    Toot
    Last edited by Toot; April 27th, 2004 at 04:24 AM.
    Some cause happiness wherever they go; others, whenever they go.

  10. #10
    Join Date
    Apr 1999
    Posts
    27,449
    Originally posted by yiannakop
    I've explained in another thread why I don't use vector class. I want some extra features and I want a class created by me, not overloaded or sth else.
    What are these "extra features" for why you can't use vector? It would solve all of your problems and make your code more maintainable.

    Your class has a member that is a pointer to dynamic memory, but ArrayD has no assignment operator or copy constructor. It will fail this simple test:
    Code:
    int main()
    {
       ArrayD a(10);
       ArrayD b = a;  // copy construction (trouble)
       ArrayD c;
       c = a;   // assignment (trouble)
    }  // destruction  ( deletion error! )
    If you are not aware of why your class fails this simple test, or how to write a copy constructor or op =, then IMO this is more a reason why you should use C++ containers. The people who wrote the std::vector code worked pretty hard at it so as to make your coding easier to handle. Usage of containers would make your class copyable and assignable without writing a user-defined copy constructor and operator = (and destructor).

    Regards,

    Paul McKenzie

  11. #11
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    I'm a little confused as to what the actual situation you
    have is. In your first post, you are returning a pointer
    to new'ed memory. In a later post, you say you are
    returning an OBJECT of type Array (or ArrayD ?).

    If you are returning and object, you should be OK
    (assuming the copy-ctor etc. are coded correctly).

  12. #12
    Join Date
    Feb 2004
    Location
    USA - Florida
    Posts
    729
    I think he's creating pointers-to-ArrayD and passing those to the functions and each function creates new ArrayD objects and returns there pointer.

    Instead of passing a pointer, how about passing-by-reference and maybe return-via-reference instead?
    Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html

  13. #13
    Join Date
    Apr 1999
    Posts
    27,449
    Originally posted by cma
    Instead of passing a pointer, how about passing-by-reference and maybe return-via-reference instead?
    Then he needs the copy/assignment to be coded and work correctly. That's the problem with pointers -- you never know that your class is really full of bugs until you start to copy and assign instances of your classes. Exclusive usage of pointers hides all of these memory bugs.

    That's the price you pay when your object contains pointers to dynamic memory, you now have the "luxury" of writing more code to make your class behave properly (which means more code to maintain, get wrong, etc.). I wished that would be emphasized by more C++ books and tutorials. New C++ programmers would then start to appreciate container classes instead of usage of raw pointers.

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured