Gee*_*ega 3 c arrays function bus-error
像往常一样,我在这里阅读了很多帖子。我发现了一篇关于一般总线错误的特别有用的帖子,请参阅此处。我的问题是我无法理解为什么我的特定代码会给我一个错误。
我的代码是自学C语言的一次尝试,是对我学Java时做的一个游戏的修改。我的游戏的目标是获取一个巨大的 5049 x 1 文本文件。随机选择一个单词,将其打乱并尝试猜测它。我知道如何做到这一切。所以无论如何,文本文件的每一行都包含一个单词,例如:
5049
must
lean
better
program
now
...
Run Code Online (Sandbox Code Playgroud)
所以,我在C中创建了一个字符串数组,尝试读取这个字符串数组并将其放入C中。我没有做任何其他事情。一旦我将文件放入 C 中,其余的事情就很容易了。更奇怪的是它遵守了。当我用./blah命令运行它时,我的问题出现了。
我得到的错误很简单。它说:
zsh: bus error ./blah
Run Code Online (Sandbox Code Playgroud)
我的代码如下。我怀疑这可能与内存或缓冲区溢出有关,但这完全不科学,而且是一种直觉。所以我的问题很简单,为什么这个 C 代码会给我这个总线错误消息?
#include<stdio.h>
#include<stdlib.h>
//Preprocessed Functions
void jumblegame();
void readFile(char* [], int);
int main(int argc, char* argv[])
{
jumblegame();
}
void jumblegame()
{
//Load File
int x = 5049; //Rows
int y = 256; //Colums
char* words[x];
readFile(words,x);
//Define score variables
int totalScore = 0;
int currentScore = 0;
//Repeatedly pick a random work, randomly jumble it, and let the user guess what it is
}
void readFile(char* array[5049], int x)
{
char line[256]; //This is to to grab each string in the file and put it in a line.
FILE *file;
file = fopen("words.txt","r");
//Check to make sure file can open
if(file == NULL)
{
printf("Error: File does not open.");
exit(1);
}
//Otherwise, read file into array
else
{
while(!feof(file))//The file will loop until end of file
{
if((fgets(line,256,file))!= NULL)//If the line isn't empty
{
array[x] = fgets(line,256,file);//store string in line x of array
x++; //Increment to the next line
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这条线有几个问题:
array[x] = fgets(line,256,file);//store string in line x of array
Run Code Online (Sandbox Code Playgroud)
您已经读取了上一条语句的条件中的行if:您要操作的当前行已经在缓冲区中,现在您可以用来fgets获取下一行。
您尝试每次分配给同一个数组槽:相反,您需要为每次循环时都会递增的数组索引保留一个单独的变量。
最后,您尝试使用 复制字符串=。这只会复制引用,不会创建字符串的新副本。因此数组的每个元素都将指向相同的 buffer: line,当函数退出时,它将超出范围并变得无效。array要使用字符串填充您,您需要为数组的每个字符串创建一份副本:使用 为每个新字符串分配空间malloc,然后使用strncpy将每个字符串复制line到新字符串中。或者,如果您可以使用strdup,它会为您分配空间。
但我怀疑这是导致总线错误的原因:您将数组大小传递为x,并在循环中分配给array[x]。问题是array[x]不属于数组,数组只有0to的可用索引(x - 1)。