typedef struct {
void *elems;//address of the memory block
int elemSize; //
int logicLen;//number of existing elements in vector
int allocLen;//allocated space for the vector
} vector;
static void InsertNumbers(vector *numbers, long n, long d)
{
long k;
long residue;
for (k = 0; k < d; k++) {
residue = (long) (((long long)k * (long long) n) % d);
VectorAppend(numbers, &residue);
}
}
void VectorAppend(vector *v, const void *elemAddr)
{
void *target=(char*)v->elems + (v->logicLen * v->elemSize);
if(v->logicLen==v->allocLen){
v->allocLen*=2;
v->elems=realloc(v->elems,v->allocLen*v->elemSize);
assert(v->elems!=NULL);
}
memcpy(target,elemAddr,v->elemSize);
v->logicLen++;
}
然后,我用下面这句话来调用 InsertNumbers()
vector aVector;
VectorNew(&aVector, sizeof(long),4);
long first=139269,second=3021377;
InsertNumbers(&aVector,first , second);
好像3021377太大了……在v->elems=realloc(v->elems,v->allocLen*v->elemSize);
我发现当v->allocLen=4096时,程序崩溃并说:这可能是由于堆的损坏为什么?