C代码在断点处运行良好,但在没有断点的情况下崩溃

时间:2013-07-09 20:19:22

标签: c

我有一个c语言的代码,如果你在其中放置断点并手动遍历它,那么它运行良好,但是如果我们松开断点并让它自动运行就会崩溃。

这意味着什么?

这是功能:

void play(int map[length][length])
{
    FILE*             matrix;
    struct Coordinate startPoint;
    struct Coordinate endPoint;
    char              buffer[200];
    int               lineNumber;
    int               run = 1;
    int               direction;
    int               gaps;
    int               letter;
    int               playerX;
    int               playerY;
    int               killerX;
    int               killerY;

    startPoint.steps = -1;

    printf("enter X and Y of player");
    scanf("%d,%d", &playerX, &playerY);

    printf("enter X and Y of killer");
    scanf("%d,%d", &killerX, &killerY);

    while (run)
    {
        letter = 0;
        printf("enter direction [2]=down, [4]=left, [6]=right, [8]=up");
        scanf("%d", &direction);
        switch (direction)
        {
            case 2: playerX++; break;
            case 4: playerY--; break;
            case 6: playerY++; break;
            case 8: playerX--; break;
        }

        startPoint.x = killerX;
        startPoint.y = killerY;
        endPoint.x   = playerX;
        endPoint.y   = playerY;

        root = insertDataToTree(root, startPoint.x, startPoint.y, map, startPoint.steps);
        findShortestPath(root, startPoint, endPoint);

        matrix = fopen("space.txt", "r");
        for (lineNumber = 0; lineNumber < 15; lineNumber++)
        {
            fgets(buffer, 200, matrix);
        }

        for (gaps = 0; gaps < 4; letter++)
        {
            if (buffer[letter] == ' ')
            {
                gaps++;
            }
        }

        fclose(matrix);

        switch (buffer[letter + 1])
        {
            case 'd': killerY++; break;
            case 'l': killerX--; break;
            case 'r': killerX++; break;
            case 'u': killerY--; break;
        }

        if (playerX == killerX && playerY == killerY)
        {
            run = 0;
        }
    }
}

这是我遇到的错误:     Project 2.exe中0x779615de处的未处理异常:0xC0000005:访问冲突读取位置0x00440000。

由于

1 个答案:

答案 0 :(得分:0)

如各种评论中所述,存在许多问题。总结:

  • 您不会检查scanf()来电是否成功。这可能会导致您使用未初始化的变量。
  • 您从matrix读取的方式,您只查看最后一行的最后N % 199个字节(最后一行是N个字节长)。

最后,您可能正在读取此循环中的输入缓冲区:

    for(gaps=0;gaps<4;letter++)
        if(buffer[letter]==' ')
            gaps++;

如果行中的间隙少于4,则会在缓冲区末尾读取以查找更多间隙。你应该停在字符串的末尾。

    for(gaps=0;gaps<4;letter++) {
        if (buffer[letter]=='\0') break;
        if(buffer[letter]==' ')
            gaps++;
    }