【问题标题】:Passing and realloc a pointer into a funcion将指针传递并重新分配到函数中
【发布时间】:2017-04-17 19:26:19
【问题描述】:

嗨,我有一个要在函数中操作的指针,所以我使用双指针作为函数的参数。问题是当它调用 realloc 时会生成一个分段错误。这里有我的代码

 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
  • *off=(int*)realloc(*off, sizeof(int)*(++count)); 您必须将指针结果保存在第一位。您的代码正在泄漏。
  • @πάνταῥεῖ:在检查realloc 的结果之前覆盖原始指针是个坏主意。
  • @Olaf 另外,是的。
  • Something like this(代码注释掉了,但是所有 malloc 和 realloc 的东西都被 std::vector 取代了)。您为 realloc 编写的所有代码都缩减为一行。

标签: c++ pointers arguments


【解决方案1】:

我在名为 int* off 的函数中使用另一个指针解决了问题,我使用它代替了 off。最后我写 *off=offe;它有效

【讨论】:

  • 首先,我遇到了指针问题。我通过添加另一个指针来解决它。现在我有两个问题!
  • 我解决了没有使用 off(函数的参数)来使用 realloc。我使用了另一个指针,最后我用来将他的内存地址保存到关闭双指针中
猜你喜欢
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 2012-07-03
  • 2019-06-12
  • 2013-04-14
  • 2014-06-03
相关资源
最近更新 更多