Thread: my vector class..easy dynamic arrays

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    A couple things. The first doesn't really matter much, but you are using manual pointer arithmetic when indexing is shorter, and more clear. Why use

    *(m_array + i)

    when you can just do

    m_array[i]

    Some times it makes sense to use manual pointer arithmetic (IE when you are incrementing the pointer without using a variable (example: ++m_array) but here it just brings down readability.



    The second problem is VERY big.

    You've created a [probable] memory leak.

    You use the false assumption that a dynamically allocated array of 1 element can be deleted without using delete []. That is not true!

    When you dynamically allocate an array, two things are actually allocated. The array itself and some way of keeping track of the size of the array so that when you delete it, it will be deleted fully. Using delete [] checks that value, deletes the corresponding amount of data, but also deletes the data that was used to keep track of the size of the array internally.

    The way this is usually done by the compiler is the extra data is placed before the array in memory.

    So

    m_array = new Datatype[Amount];

    will actually allocate something similar to this type (pseudo-code):

    struct
    {
    inttype SizeOfArray; // = Amount
    Datatype Array[Amount];
    }

    //Where inttype would be an integer type of size pointer to primitive built-in-type

    When you call new, it will return a pointer to the Array member (not the beginning of the struct) so that you can use the array as normal.

    Then, when you call delete [] on it, it knows to go back sizeof(inttype) in memory to check how much to delete but it also has to delete itself as well.

    If you call delete without the brackets, then you totally miss the extra data.

    Code:
    if(m_size > 1)
    	{
    		delete [] m_array;
    	}
    	else
    	{
    		delete m_array;
    	}
    Should just be

    delete [] m_array;

    plain and simple. Otherwise you'll have problems in the future.
    Last edited by Polymorphic OOP; 02-01-2003 at 05:33 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Struct types and dynamic arrays
    By simone.marras in forum C Programming
    Replies: 6
    Last Post: 03-14-2009, 10:56 AM
  2. Dynamic Arrays?
    By screenfreak in forum C Programming
    Replies: 2
    Last Post: 10-30-2006, 11:38 AM
  3. Creating New Dynamic Arrays
    By mas0nite in forum C++ Programming
    Replies: 8
    Last Post: 10-19-2006, 02:59 PM
  4. Dynamic two dimensional arrays
    By ThWolf in forum C++ Programming
    Replies: 14
    Last Post: 08-30-2006, 02:28 PM
  5. 2D arrays with functions made easy
    By goran in forum C Programming
    Replies: 1
    Last Post: 09-17-2001, 12:08 PM