具体读取 13 行时出现分段错误
char **getLines(FILE *pFile)
{
int nLines = 0;
size_t memRes = 0;
char **lines = malloc(memRes);
char *current = (char*) malloc(20);
while(fgets(current, 20, pFile) != NULL)
{
memRes += sizeof(char*);
lines = realloc(lines, memRes);
lines[nLines] = malloc(20);
strcpy(lines[nLines], current);
nLines++;
}
free(current);
return lines;
}
void printLines(char **lines)
{
int lineI = 0;
while(lines[lineI] != NULL)
{
printf("%s", lines[lineI]);
lineI++;
}
}
首先我得到线条然后打印它们。奇怪的是,当我的代码读取了 13 行代码并打印它们时,它就失败了。打印最后一行后出现分段错误。它适用于 12 行和 14 行。
char **getLines(FILE *pFile)
{
int nLines = 0;
size_t memRes = 0;
char **lines = malloc(memRes);
char *current = (char*) malloc(20);
while(fgets(current, 20, pFile) != NULL)
{
memRes += sizeof(char*);
lines = realloc(lines, memRes);
lines[nLines] = malloc(20);
strcpy(lines[nLines], current);
nLines++;
}
free(current);
return lines;
}
void printLines(char **lines)
{
int lineI = 0;
while(lines[lineI] != NULL)
{
printf("%s", lines[lineI]);
lineI++;
}
}
First I get the lines then I print them. The odd thing about it is that my code fails when it has read exactly 13 lines of code and then prints them. I get a segmentation fault after printing the last line. It works with 12 lines and with 14 lines perfectly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 printLines 函数中,“while(lines[lineI] != NULL)”
发生的情况是,lines[lineI] 不是 NULL,只是最后还没有分配。因为 lineI 大于 nLines,所以它会出现段错误。您必须将 nLines 传递到函数中并使用它来检查边界。 “同时(lineI < nLines)”
In your printLines function, "while(lines[lineI] != NULL)"
What is happening is that lines[lineI] isn't NULL, it just hasn't been allocated at the end. So because lineI is greater than nLines, it segfaults. You have to pass nLines into the function and use that to check boundries. "while (lineI < nLines)"
线条可能有点太小了。
Lines might be a bit too small.
您假设行尾之后的内存将包含 NULL,它可能会也可能不会 - 它未初始化,因此它可以容纳任何内容。您对一些小数据集感到“幸运”,并且它恰好包含零,所以它有效。对于更大的数据集,您会遇到其中有其他内容的内存区域,并且它会失败。如果您希望超过保存 fgets() 调用数据的指针集的行为 NULL,则需要分配足够大的空间以容纳额外的指针,并将该空间设置为 NULL。
You are assuming that the memory past the end of lines will contain a NULL, which it may or may not - it is uninitialized, so it could hold anything. You are getting 'lucky' for some small data sets, and it happens to contain zeros, so it works. For bigger data sets, you are running into an area of memory that has something else in it, and it is failing. If you want lines to be NULL past the set of pointers that hold the data from the fgets() calls, you need to allocate it big enough to hold an extra pointer, and set that space to NULL.