views:

88

answers:

2

Hi guys, i'm developing an array structure just for fun. This structure, generalized by a template parameter, pre allocates a given number of items at startup, then, if "busy" items are more than available ones, a function will realloc the inner buffer . The testing code is :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template <typename T> struct darray_t {
    size_t items;
    size_t busy;
    T     *data;
};

#define DARRAY_REALLOC_ITEMS_STEP 10

#define da_size(da) (da)->busy

template <typename T>
void da_init( darray_t<T> *da, size_t prealloc ){
    da->items = prealloc;
    da->busy  = 0;
    da->data  = (T *)malloc( sizeof(T) * prealloc );
}

template <typename T> T *da_next( darray_t<T> *da ){
    if( da->busy >= da->items ){
        da->data   = (T *)realloc( da->data, sizeof(T) * DARRAY_REALLOC_ITEMS_STEP );
        da->items += DARRAY_REALLOC_ITEMS_STEP;
    }
    return &da->data[ da->busy++ ];
}

int main(){
    darray_t<int> vi;
    int *n;

    da_init( &vi, 100 );

    for( int i = 0; i < 101; ++i ){
        n = da_next(&vi);
        *n = i;
    }

    for( int i = 0; i < da_size(&vi); ++i ){
        if( vi.data[i] != i ){
            printf( "!!! %d != %d\n", i, vi.data[i] );
        }
    }

    return 0;
}

As you can see, i prealloc 100 integer pointers at the beginning and then i realloc them with 10 more pointers at time. In the main function, i perform a for loop to check items integrity and, if an array item is not as i expect, i print its value and ... you know what ? I have the following message :

!!! 11 != 135121

In fact, item at index 11, that should be '11', is 135121 !!!! :S

Can you tell me if my code is not correct?

Thanks

NOTE I perfectly know that mixing C and C++ this way is ugly, and i know too that this structure would screw up if used, for instance :

darray_t<std::string>

This is just a test for int pointers.

+1  A: 

The size of the block is incorrect:

da->data   = (T *)realloc( da->data, sizeof(T) * DARRAY_REALLOC_ITEMS_STEP );

The entire block is as big as the increment. Try

da->busy + sizeof(T) * DARRAY_REALLOC_ITEMS_STEP
Potatoswatter
+3  A: 

realloc does not automatically grow the piece of memory - you'll have to do that. Do e.g.:

da->data=(T*)realloc(da->data, sizeof(T)*(da->items+DARRAY_REALLOC_ITEMS_STEP));

(and you should handle realloc returning NULL)

nos