Giorgi Cercvadze Giorgi Cercvadze - 1 month ago 15
C Question

using struct value in realloc gives segmentation fault

in C I have a struct which looks like this

typedef struct {
void * elems;
int logLen;
int allocLen;
int elemSize;
void (*vecFree)(void *);
int initAlloc;
} vector;`


i also have functions

void VectorNew(vector *v, int elemSize, VectorFreeFunction freeFn, int initialAllocation)
{ printf("%s\n" , "vecNew");
assert(elemSize > 0);
assert(initialAllocation >-1);
if(initialAllocation == 0) {
v->initAlloc = 15;
v->allocLen = v->initAlloc;
}
else {
v->initAlloc = initialAllocation;
v->allocLen = v->initAlloc;
}
v->elemSize = elemSize;
v->elems = malloc(v->elemSize*v->allocLen);
v->logLen = 0;
v->vecFree = freeFn;
}


and

void VectorAppend(vector *v, const void *elemAddr)
{ printf("%s\n" , "vecAppend");
if(v->logLen == v->allocLen)
growVector(v);
void * dest = point(v,v->logLen,v->elemSize);
dest = memcpy(dest,elemAddr,v->elemSize);
v->logLen++;
}


and the growVector function looks like this

void growVector(vector *v){
printf("%s\n" , "vecGrow");
v->allocLen +=v->initAlloc;
v->elems = realloc(v->elems,(v->elemSize) * (v->allocLen));
}


ok so the problem is during vectorNew i pass elemSize = 1, initialAllocation = 4 and other arguments properly
then i use vectorAppend 4 times. after that i use vecotrAppend one more time but allocLen is equal to logLen so it has to go to vectorGrow and thats where segmentation fault takes place. any suggestion ?

Answer

You use your macro point wrong.

void VectorAppend(vector *v, const void *elemAddr)
{   
    printf("%s\n" , "vecAppend");
    if(v->logLen == v->allocLen)
        growVector(v);

    void * dest = point(v->elems,v->logLen,v->elemSize); // starting point is at v->elems
    dest = memcpy(dest,elemAddr,v->elemSize);
    v->logLen++;
}
Comments