我正在做家庭作業,我遇到了這些問題。 我在調用allocate()時得到EXC_BAD_ACCESS;爲什麼我會用這些C++函數獲取EXC_BAD_ACCESS?
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;
}
這裏是我的expandPool方法:
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;
}
爲什麼你覺得你需要用malloc和memcpy等來完成所有這些低級C風格的內存管理?正如你現在看到的那樣,這很容易出錯。 – 2012-02-04 20:19:08
像'memcpy(&free,free,...)'這樣的行和'expandPool()'中應該實現的循環是什麼? 'pool = tmp中的刪除;刪除[] tmp;'是絕對錯誤的。 – 2012-02-04 20:31:45
@PaulR可能是分配的要求。我記得我在Uni時有那些瘋狂的限制。 – Krizz 2012-02-04 20:36:16