问题
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;
}
回答1:
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 copying sizeof(char *)
bytes. Assuming free is declared as char *free;
then that is ok, so it must be the content of free
you are writing from.
Stylistically, using memcpy
like this -- to copy a single pointer value -- is confusing. You are better off with something like:
free = *(char **)free;
which is equivalent to your:
memcpy(&free,free,sizeof(char*));
The value of sizeof(char*)
varies between systems -- 4
on 32-bit and 8
on 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:
tmp2 = new char;
Here, you are allocating a block of memory with sizeof(char)
which is 1
. This needs to be at least:
tmp2 = new char[sizeof(char *)];
NOTE: Calling your variable free
will override the free
function, 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
, tmp2
and free
). 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.
回答2:
There are several problems in your code. One that stands out to me is this part:
pool = tmp;
delete [] tmp;
To me, this makes pool
point to deleted memory. Using pool
later in the code causes undefined behavior, which can not be explained by the language. Failure elsewhere in the code is just to be expected.
来源:https://stackoverflow.com/questions/9144166/why-am-i-getting-exc-bad-access-with-these-c-functions