App*_*ash 0 c pointers char segmentation-fault
出于某种原因,这段代码是segfaulting,原因我无法找到.
char *read_line(FILE *fp)
{
char *out;
int counter = 0;
char c = getc(fp);
while (c != '\n' && c != EOF)
{
*(out + counter) = c;
counter++;
c = getc(fp);
}
if (c == EOF || feof(fp))
{
return NULL;
}
*(out + counter) = '\0';
return out;
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过运行它gdb,并告诉我段错误是在*(out + counter) = c;.我无法弄清楚我做错了什么,还有其他人吗?
你没有给任何值赋值out,所以它可能指向一些无效的内存地址.
你可能想要做的是先找到数据的长度,然后分配所需的内存量,然后将实际数据读入分配的内存:
char *out;
int counter = 0;
char c = getc(fp);
while (c != '\n' && c != EOF) {
counter++;
c = getc(fp);
}
out = malloc(counter+1);
fseek(fp,0,SEEK_SET);
counter = 0;
c = getc(fp);
while (c != '\n' && c != EOF) {
*(out + counter) = c;
counter++;
c = getc(fp);
}
*(out + counter) = 0;
Run Code Online (Sandbox Code Playgroud)
free(out)当你完成使用它时别忘了......
顺便说一下for,你可以简单地使用,而不是第二个循环fgets(out,count,fp).
| 归档时间: |
|
| 查看次数: |
355 次 |
| 最近记录: |