c - 为什么这个 C 代码给我一个总线错误?

标签 c arrays function bus-error

像往常一样,我在这里阅读了很多帖子。我发现了一个关于一般总线错误的特别有用的帖子,请参阅 here .我的问题是我不明白为什么我的特定代码会给我一个错误。

我的代码是自学C的一次尝试,是我学习Java时做的一个游戏的修改版。我游戏的目标是获取一个巨大的 5049 x 1 文本文件。随机选择一个单词,将其打乱并尝试猜测。我知道该怎么做。所以无论如何,文本文件的每一行都包含一个词,如:

   5049
   must
   lean 
   better 
   program 
   now
   ...

所以,我在C中创建了一个字符串数组,尝试读取这个字符串数组并将其放入C中。我没有做任何其他事情。一旦我将文件放入 C 中,剩下的就很容易了。更奇怪的是它符合要求。当我使用 ./blah 命令运行它时,我的问题就来了。

我得到的错误很简单。它说:

zsh: bus error ./blah

我的代码如下。我怀疑这可能与内存或缓冲区溢出有关,但这完全是不科学的,而且是一种直觉。所以我的问题很简单,为什么这个 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 
           }    
        }
    }

}

最佳答案

这条线有几个问题:

array[x] = fgets(line,256,file);//store string in line x of array 
  • 您已经阅读了前一个 if 语句的条件行:您要操作的当前行已经在缓冲区,现在您使用 fgets 获取行。

  • 您每次都试图分配给同一个数组槽:相反,您需要为数组索引保留一个单独的变量,该变量在每次循环中递增。

  • 最后,您尝试使用 = 复制字符串。这只会复制引用,不会创建字符串的新副本。因此数组的每个元素都将指向同一个缓冲区:line,这将超出范围并在您的函数退出时变为无效。要用字符串填充 array,您需要为数组复制每个字符串:使用 malloc 为每个新字符串分配空间,然后使用 strncpy将每个 line 复制到您的新字符串中。或者,如果您可以使用 strdup ,它将负责为您分配空间。

但我怀疑这是您的总线错误的原因:您将数组 size 作为 x 传递,并且在循环中,您正在分配到 array[x]。这个问题是 array[x] 不属于数组,数组只有 0(x - 1)< 的可用索引

关于c - 为什么这个 C 代码给我一个总线错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11727383/

相关文章:

将sqlite连接到C程序

c - 将宏扩展为无代码 : "do {} while (0)" or "while (0) {}"

c++ - 如何将 std::array 转换为 std::tuple?

将值写入其他变量后,C 在函数中释放 int 数组

javascript - 如何跟踪同一函数的多次运行?

function - 如何自引用一个函数?

c++ - 试图编写一个递归函数来计算总和为该数字的序列数 C++

c - 无法使用我的套接字服务器程序连接多个客户端

c - 如何重载C中的函数?

javascript - 如何根据数组中的最后一个索引隐藏元素?