I am doing a homework assignment and I am running into these issues.
I am getting EXC_BAD_ACCESS when I call allocate();
void* Pool::allocate() {
if( free == NULL) {
this->expandPool();
}
void* tmp = free;
void* mem = malloc(elemSize);
memcpy(&free,free,sizeof(char*)); //exec bad access right here
memcpy(tmp,mem,sizeof(elemSize));
return tmp;
}
Here is my expandPool method:
void Pool::expandPool() {
poolSize++;
// Is this the first time?
if(poolSize <= 1)
pool = new char*[poolSize];
else {
char** tmp = new char*[poolSize];
memcpy(tmp,pool,sizeof(pool));
delete [] pool;
pool = tmp;
delete [] tmp;
}
char* tmp = NULL;
char* tmp2;
for(int i = 0; i < blockSize; i++) {
tmp2 = new char;
memcpy(tmp2,&tmp,sizeof(char*));
tmp = tmp2;
}
pool[poolSize - 1] = tmp;
free = tmp;
}
If you google
EXC_BAD_ACCESS, you will find that it is because you are accessing memory outside an allocated memory block. This can be for several reasons.So, lets start at the failing point — the
memcpy: you are writing to the free pointer (&free) the content of free (free), and are copyingsizeof(char *)bytes. Assuming free is declared aschar *free;then that is ok, so it must be the content offreeyou are writing from.Stylistically, using
memcpylike this — to copy a single pointer value — is confusing. You are better off with something like:which is equivalent to your:
The value of
sizeof(char*)varies between systems —4on 32-bit and8on 64-bit — so the amount of space allocated must be at least that big.Ok, so lets look at the expandPool method to see what free is set to:
Here, you are allocating a block of memory with
sizeof(char)which is1. This needs to be at least:NOTE: Calling your variable
freewill override thefreefunction, so you will need to explicitly access that function by writing::free.I’d start off by drawing a diagram of what you want the memory layout of the pool to be and how it will look/change (a) when empty, (b) when allocating a chunk that is free and (c) when allocating a chunk when you need to expand the pool. Annotate the diagram with the different variables (
pool,tmp,tmp2andfree). This will give you an idea of what you need to do and what the code should look like.Having a good understanding of the data structures and algorithms (through creating the diagrams) will help you get the code right.