无法运行此 C 代码:没有错误或警告,但程序只是崩溃



我没有抱怨代码结果,但当我运行代码时,IDE立即停止工作。

我尝试了许多IDE和编辑器,但仍然什么都不做,也没有错误或警告。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define NUM_STRING 4
#define MAX_STRING_SIZE 40
char* getWord()
{
static char words[NUM_STRING][MAX_STRING_SIZE] = {
"game",
"hello",
"program",
"pointer"
};
int randomIndex = rand() % 4;
char* selectedWord = words[randomIndex];
return selectedWord;
}
char GuessLetter()
{
char letter;
int value=1;
while(value)
{
printf("nmake a guess: ");
if(scanf("%c", &letter) != 1)
{
printf("Please re-enter a letter");
}
else
{
value = 0;
}
}
return letter;
}
int checkchar(char* PW)
{
int i, len = strlen(PW);
for(i=0; i < len; i++)
{
if(PW[i]=='_')
{
return 1;
}
}
return 0;
}
char* printafter( char *currentWord, int len, char letter, char *PW)
{
int i;
for(i=0; i<len; i++)
{
if(letter == currentWord[i])
{
PW[i] = letter;
}
printf("%c ", PW[i]);
}
return PW;
}
void startGame()
{
char* currentWord = getWord();
char *PartialWord=NULL;
int i, length = strlen(currentWord);
printf("%sn", currentWord);
for(i=0; i<length; i++)
{
PartialWord[i] = '_';
printf("_ ");
}
if(!(PartialWord = (char*)malloc(length)))
{
printf("Sorry there was an allocation error! ");
exit(1);
}
while(checkchar(PartialWord))
{
PartialWord = printafter(currentWord, length, GuessLetter(), PartialWord);
}
}
int main() {
srand(time(NULL));
startGame();
return 0;
}

代码中的主要问题是,您试图在分配数据之前将数据分配给PartialWord数组!这会导致未定义的行为,并且几乎任何都可能发生,包括数据的部分输出,然后是程序崩溃。

只需将malloc代码移动到,然后startGame函数中的for循环(如下所示(。。。当你完成它时,记得free()记忆:

void startGame()
{
char* currentWord = getWord();
char* PartialWord = NULL;
int i, length = strlen(currentWord);
// You MUST have this allocation BEFORE you assign the '_' characters in the for loop!
if (!(PartialWord = malloc(length))) { // Also, yoi don't need to (and shouldn't) cast the malloc return
printf("Sorry there was an allocation error! ");
exit(1);
}
printf("%sn", currentWord);
for (i = 0; i < length; i++) {
PartialWord[i] = '_'; // In your code, PartialWord is NULL when you do this!
printf("_ ");
}
while (checkchar(PartialWord)) {
PartialWord = printafter(currentWord, length, GuessLetter(), PartialWord);
}
free(PartialWord); // Remember to free the memory when you're done with it!
}

关于是否强制转换malloc的结果的问题,请参阅此处:我强制转换malloc的结果吗?。

请随时要求任何进一步的澄清和/或解释。

相关内容

最新更新