C Hangman程序调试辅助程序(异常终止:6错误)

时间:2018-12-09 03:20:32

标签: c debugging abort

我正在用C创建典型的hangman程序,代码可以编译并完美运行,直到我添加3行代码(25-29),这些代码在用户选择了所需的游戏模式后将字符串加载到结构中。

运行程序时,除非用户做出选择以执行第25-29行中的“ if”语句(有注释标识该语句),否则所有功能都将起作用,然后终端将返回“ Abort trap:6”错误

研究并尝试调试我的代码后,我无法找到要写入的内存(尚未初始化)。代码中的所有其他内容都可以正常工作,因此我仅在寻找有关此错误的具体建议:

char temp2[20]="", phrase[15]="cest la vie";
int guess=0, correct=0, banksize=0, wordsize=0, wordNum=0;
int n, select=0;
time_t t;
strcpy(hangman.guess,temp2);
hangman.incorrect=0;
hangman.wordcount=0;

//This section introduces the user to the game
printf("\nWelcome to Dakota's Amazing Hangman Program!!!(TM)\n");
printf("---------------------------------------------------\n");
printf("I will select a word or phrase at random. \n");
printf("Guess a letter wrong 10 times and you'll hang.\n");
printf("For a word, type and enter 0. For an expression, enter 1:");
scanf("%i",&select);

//This section requests a file and loads it into struct
if(select==0)
{
   InputFile();
   banksize=LoadWordbank();
   srand((unsigned)time(&t));
   wordNum=rand() % banksize;
}
if(select==1)  //The issue is with the addition of this if statement
{
   strcpy(hangman.word[0],phrase);
   wordNum=0;
} 

wordsize=strlen(hangman.word[wordNum]);
char temp3[wordsize];
for(n=0;n<wordsize;n++)
   temp3[n]='_';
strcpy(hangman.progress,temp3);

这是我的结构定义供参考,它是一个全局变量:

struct game
{
  char word[30][15];
  char progress[8];
  char guess[20];
  int incorrect;
  int wordcount;
};
struct game hangman;

此外,我是这个论坛的新手,因此欢迎您提供有关问题格式的任何有用建议。

1 个答案:

答案 0 :(得分:0)

在与一些同学合作并确定问题与如何将字符串加载到结构无关之后,我们确定它因此必须是一个对单词长度敏感的变量问题。

仔细检查后,似乎我已经扩展了所有变量的大小,以说明除了struct中的此变量外,还添加了一个大于7个字母的单词:

char progress[8];

这是我尝试将较大的字符串复制到hangman.progress变量中的代码的第33行的问题。

将其扩展为[15]的安全分配后,我不再收到任何错误。现在的代码如下所示:

struct game
{
  char word[30][15];
  char progress[15];
  char guess[20];
  char bodypart[10][15];
  int incorrect;
  int wordcount;
};
struct game hangman={"cest la vie"};

...

//This section loads the arrays in the hangman struct
char temp2[20]="", phrase[]="cest la vie";
int guess=0, correct=0, banksize=0, wordsize=11, wordNum=0;
int n, select=0;
time_t t;
strcpy(hangman.guess,temp2);
hangman.incorrect=0;
hangman.wordcount=0;
LoadBody();

//This section introduces the user to the game
printf("\nWelcome to Dakota's Amazing Hangman Program!!!(TM)\n");
printf("---------------------------------------------------\n");
printf("I will select a word or phrase at random. \n");
printf("Guess a letter wrong 10 times and you'll hang.\n");
printf("For a word, type and enter 0. For an expression, enter 1:");
scanf("%i",&select);

//This section requests a file and loads it into struct
if(select==0)
{
   InputFile();
   banksize=LoadWordbank();
   srand((unsigned)time(&t));
   wordNum=rand() % banksize;
   wordsize=strlen(hangman.word[wordNum]);
}

char temp3[wordsize];
for(n=0;n<wordsize;n++)
   temp3[n]='_';
strcpy(hangman.progress,temp3);

if(select==1)
   wordsize=wordsize-2;