【发布时间】: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编写的所有代码都缩减为一行。