您好我有一個指針,我想在一個函數中操作,所以我使用一個雙指針作爲函數的參數..問題是,當它調用realloc時產生了一個segmantation錯誤..這裏有我的代碼傳遞並將一個指針重新分配到一個函數
Loader::Loader(char* filename)
{
file_desc=open(filename,O_RDONLY);
if(file_desc<0) {
std::cout<<"Error to open file..."<<std::endl;
}
offsets=(int*)malloc(sizeof(int));
this->detect_element(&offsets,'o',0);
}
void Loader:: detect_element(int** off,char p,int loffset,int end)
{
char buffer;
int count=1;
int i=0;
std::cout<<"Starting with caracter "<<p<<" from "<<loffset;
if(end!=-1)
{
std::cout<<" and ending to "<<end<<std::endl;
}else{
std::cout<<" and ending to the end"<<std::endl;
}
lseek(file_desc,loffset,SEEK_SET);
while(read(file_desc,&buffer,1)>0)
{
if(buffer==p && state==CR)
{
*off[count-1]=i;
*off=(int*)realloc(*off,
sizeof(int)*(++count));
}
else if(buffer=='\n'){
state=CR;
}
else{
state=-1;
}
i++;
if(end!=-1&&end==i){break;}
}
std::cout<<"Number of objs detected is "<<this->Length(*off)
<<count<<std::endl<<std::endl;
}
保存你自己的指針地獄並使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector) – NathanOliver
'* off =(int *)realloc (* off, sizeof(int)*(++ count));'您必須將指針結果保存在第一位。您的代碼泄漏。 –
@πάνταῥεῖ:在檢查'realloc'的結果之前覆蓋原始指針是個壞主意。 – Olaf