2016-12-02 91 views
0

您好我有一個指針,我想在一個函數中操作,所以我使用一個雙指針作爲函數的參數..問題是,當它調用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; 
} 
+7

保存你自己的指針地獄並使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector) – NathanOliver

+0

'* off =(int *)realloc (* off, sizeof(int)*(++ count));'您必須將指針結果保存在第一位。您的代碼泄漏。 –

+0

@πάνταῥεῖ:在檢查'realloc'的結果之前覆蓋原始指針是個壞主意。 – Olaf

回答

0

我解決了在函數中使用另一個指針int * offe,我用它代替關閉。最後,我寫* off = offe;它可以工作

+0

首先,我有一個指針問題。我通過添加另一個指針來解決它。現在我有兩個問題! –

+0

我解決了沒有使用關閉(函數的參數)使用realloc。我已經使用了另一個指針,最後我用它將內存地址保存到關閉的雙指針中 –

相關問題