eteran / c-vector

A dynamic array implementation in C similar to the one found in standard C++
MIT License
737 stars 109 forks source link

Using "cvector_insert" in "x64" architecture will cause crash #44

Closed w4454962 closed 1 year ago

w4454962 commented 1 year ago

Also, if you use "cvector_set_size" before "cvector_push_back", the no effect.

eteran commented 1 year ago

Can you please share some examples to replicate the issue? I'll work up a fix asap.

w4454962 commented 1 year ago

#include<stdarg.h>

struct data_t {
    int num;
    int a, b, c, d;
};

struct data_t** test(size_t count, ...) {
    cvector_vector_type(struct data_t*) vec = NULL;

    va_list valist;
    va_start(valist, count);

    for (size_t i = 0; i < count; i++) {
        int num = va_arg(valist, int);
        struct data_t* data = calloc(sizeof(struct data_t), 1);
        data->num = num;
        cvector_insert(vec, 0, data);
    }
    va_end(valist);

    return vec;
} 

int main(int argc, char **argv)
{
    for (size_t a = 0; a < 1000; a++) {
        struct data_t** vec = test(4, 1, 2, 3, 4);

        for (size_t i = 0; i < cvector_size(vec); i++) {
            int num = vec[i]->num;
            printf("%i %i = %i\n", a, i, (vec[i])->num);
        }

        cvector_free(vec);
    }

 return 0;
}

This code will generate exceptions in the x86/x64 msvc environment. After replacing "cvector_insert" with "cvector_push_back", there will be no exceptions.

eteran commented 1 year ago

Thanks, I'll take a look

eteran commented 1 year ago

OK, this was a doozy to identify but I think it's fixed now. There was an off by one error when shuffling things around combined with some lifetime issues.

Please re-open or open a new issue if you continue to have a problem.

Thanks for reporting!