Search code examples
carraysadtrealloc

What's causing my array to be filled with unwanted numbers


I am trying to implement a set ADT using dynamic arrays. I have a set for odd and even numbers. When a array is full I use realloc to get a bigger array. The problem is that this also seems to fill the array with unwanted numbers.

struct set
{
    void **array;
    int numitems;
    int maxitems;
    cmpfunc_t cmpfunc;
};

.

void set_add(set_t *set, void *elem)
{
    if (!set_contains(set, elem))
    {
        if (set->numitems + 1 >= set->maxitems) // Make new bigger array if full
        {
            void **new_array = realloc(set->array, sizeof(void *) * set->maxitems * 2);
            if (new_array == NULL)
                printf("Error");
            set->maxitems *= 2;
            set->array = new_array;
        }
        set->array[set->numitems] = elem;
        set->numitems++;
    }
}

In main i use this to add numbers.

for (i = 0; i <= n; i++) {
    if (i % 2 == 0)
        set_add(evens, numbers[i]);
    else
    {
        printset("Odd numbers":, odds);
        set_add(odds, numbers[i]);
    }
}

This is the output I get.

Output:

  • Odd numbers: 1

  • Odd numbers: 1 3

  • Odd numbers: 1 3 5

...

  • Odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29

  • Odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31

  • Odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 17 18 19 20 21 22 23 24 25 26 27 28 29 30

  • Odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 18 19 20 21 22 23 24 25 26 27 28 29 30

...

After 31 is added, the array maxsize (=16) is doubled. Any ideas what causes the rest of the array to be filled? This is just a small part of the code, so if nothing here seems to be the cause I can post more.

=== Addition info: ===

static void printset(char *prefix, set_t *set)
{
    set_iter_t *it;

    printf("%s", prefix);
    it = set_createiter(set);
    while (set_hasnext(it)) {
        int *p = set_next(it);
        printf(" %d", *p);
    }
    printf("\n");
    set_destroyiter(it);
}

.

set_iter_t *set_createiter(set_t *set)
{
    set_iter_t *iter = malloc(sizeof(set_iter_t));
    if (iter == NULL)
        return NULL;
    bobsort(set);
    iter->set = set;
    iter->cur = 0;

    return iter;
}

int set_hasnext(set_iter_t *iter)
{
    if (iter->set->array[iter->cur] == NULL)
        return 0;
    else
        return 1;
}

void *set_next(set_iter_t *iter)
{
    if (iter->set->array[iter->cur] == NULL)
        return NULL;
    else
    {
        void *elem = iter->set->array[iter->cur];
        iter->cur++;
        return elem;
    }
}

It's for an assignment, so I'm following the function signatures. I'm used to make adt list with linked list and not arrays.


Solution

  • In function set_add you should change the if condition:

     if (set->numitems + 1 >= set->maxitems) // Make new bigger array if full
    

    to

    if (set->numitems  >= set->maxitems) // Make new bigger array if full