C程序中的内存错误,名称消失了吗?

Jas*_*n94 2 c

我试图制作一个简单的游戏,http://pastebin.com/BxEBB7Z6,c.目标是通过获取随机数来尽可能接近21来击败计算机.

对于每一轮,球员的名字和总和都会被呈现出来,但由于某些原因它只能在第一次运作?像这样的东西:

球员约翰总和0.球员总和9.球员总和11.

等等.

为什么玩家的名字会被展示一次,但之后没有任何其他印刷品?我不在某处重新分配:-)

我使用该功能void PrintPlayerSum(struct Player *p)将其打印出来,它第一次工作,但仅限于此.

#include <stdio.h>
#include <stdlib.h>

#include <time.h>

struct Player
{
    char name[256];
    int sum;
};

void PrintPlayerSum(struct Player *p)
{
     printf("Player %s has sum %d\n", p->name, p->sum);
}

void wait ( int seconds )
{
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}

int main()
{
    struct Player *player = malloc(sizeof(*player));
    strcpy( player->name, "John");
    player->sum = 0;

    while(1)
    {
        PrintPlayerSum(player);

        printf("Do you want another number? (y/n, q for quit) ");
        char ch;

        scanf("%s", &ch);

        if( ch == 'q' )
            break;

        if( ch == 'y' )
        {
            srand(time(NULL));

            int rnd = rand() % 13 + 1;
            player->sum += rnd;

            printf("Player got %d\n", rnd);
        }

        if( ch == 'n' || player->sum > 21)
        {
            if( player->sum > 21 )
            {
                printf("\n*** You lost the game, please try again... ***");
            }
            else
            {
                printf("\nCPU's turn\n");

                int cpusum = 0;

                while( 1 )
                {
                       if( cpusum > 21 )
                       {
                           printf("\n*** CPU lost the game with the score %d, you win! ***", cpusum);
                           break;
                       }

                       if( cpusum > player->sum )
                       {
                           printf("\n*** CPU won the game with the score %d, please try again ***", cpusum);
                           break;
                       }

                       wait(1);
                       srand(time(NULL));
                       int rnd = rand() % 13 + 1;
                       cpusum += rnd;

                       printf("CPU got %d, sum is %d\n", rnd, cpusum);
                }
            }

            break;
        }

        printf("\n\n");
    }

    /* Cleanup ******************/
    free(player);
    /****************************/

    printf("\n\n\n");
    system("PAUSE");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

har*_*ald 5

我怀疑问题是你使用scanf.你说你想要读取一个以零结尾的字符串,但是你将它填充到一个字符串中.变量在堆栈上的布局方式导致终止的零字节最终成为player-> name中的第一个char.

尝试键入"缓冲区溢出"而不是"y",你应该得到"玩家uffer溢出去......".

如果您想坚持使用scanf,您需要确保传递正确的字符串并设置目标缓冲区大小的限制.要阅读一个字符,请尝试fgetc.

编辑: 上面当然不太正确......这是一个缓冲区溢出,但它是被覆盖的播放器结构的指针.幸运的是巧合,你得到一个指向零字节的有效地址.通过输入更多内容,您很可能会遇到崩溃.