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++;
}
Then, I use the following sentence to call InsertNumbers()
vector aVector;
VectorNew(&aVector, sizeof(long),4);
long first=139269,second=3021377;
InsertNumbers(&aVector,first , second);
It seems like 3021377 is too big…
in v->elems=realloc(v->elems,v->allocLen*v->elemSize); I find that when v->allocLen=4096, the program crashes and says:This may be due to a corruption of the heap
why?
This is not a problem with the code you posted, this is a problem somewhere else.
What happens is your program corrupts the heap, and then
reallocdetects that the heap is corrupted.You will want to detect the corruption as follows:
Make sure you enable debugging symbols
Run your program through Valgrind
Edit: There is a serious error is in the code you added.
To fix it, move the calculation for
targetbelow the reallocation:Another error: There is an error in your comments, which is part of the code and I’d recommend taking comments seriously.
The comment should not say, “allocate 4*4” bytes because that is misleading: someday you’ll compile the program on a 64-bit system that isn’t Windows, and it will be 8×4 bytes. You’re better off removing the comment and just reading the code.