即使使用二维数组的内存分配也会出现分段错误
我正在尝试读取一个文件,该文件每行包含 5 个字母的单词,共 12972 行。我不确定为什么即使释放存储空间也会出现此错误。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
file = fopen("words.txt", "r"); // Opens file
char** gssArr = (char**)malloc(12972 * sizeof(char*)); // Allocates memory for 2d array
for(int i = 0; i < 12972; i++)
{
gssArr[i] = (char*)malloc(5 * sizeof(char));
}
char word[6]; // Current word being looked at from file
int current = 0; // Used for indexing x coordinate of 2d array
while(fgets(word,6,file) != NULL) // Not at end of file
{
if(word[0] != '\n') // Not at end of line
{
for(int j = 0; j < 5; j++) // Loops through all 5 letters in word, adding them to gssArr
{
gssArr[current][j] = word[j];
}
}
current++; // Index increase by 1
}
fclose(file); // Close file, free memory
free(gssArr);
I'm trying to read a file that contains a five letter word on each line for 12972 lines. I'm not sure why I'm getting this error even with freeing storage.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
file = fopen("words.txt", "r"); // Opens file
char** gssArr = (char**)malloc(12972 * sizeof(char*)); // Allocates memory for 2d array
for(int i = 0; i < 12972; i++)
{
gssArr[i] = (char*)malloc(5 * sizeof(char));
}
char word[6]; // Current word being looked at from file
int current = 0; // Used for indexing x coordinate of 2d array
while(fgets(word,6,file) != NULL) // Not at end of file
{
if(word[0] != '\n') // Not at end of line
{
for(int j = 0; j < 5; j++) // Loops through all 5 letters in word, adding them to gssArr
{
gssArr[current][j] = word[j];
}
}
current++; // Index increase by 1
}
fclose(file); // Close file, free memory
free(gssArr);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅供参考 - 您的读者循环 - 您可能需要确保当前索引不超过 12971。
FYI - your reader loop - you may want to make sure that your current index is not going beyond 12971.
你的问题在这里:
为什么?
因为即使你在队伍的最后,它也已经完成了。
一种解决方案是将其移至
if
语句内,但我建议您使用具有更大缓冲区的fgets
。详细信息
如果每行包含一个五个字母的单词,则将
读取这五个字母并以零终止它。然后下一个
fgets
将只读取“换行符”。您仍然会增加索引计数器,最后,您会在分配的内存之外进行写入。尝试
一下你就会发现问题所在。
Your problem is here:
Why?
Because it's done even when you are at the end of the line.
One solution is to move it inside the
if
statement but instead I'll recommend that you usefgets
with a much larger buffer.Details
If every line holds a five letter word then
will read the five letters and zero terminate it. Then the next
fgets
will just read the "newline". Still you increment the index counter and in the end, you write outside allocated memory.Try
and you see the problem.