You need to enable JavaScript to run this app. C语言计算机器人与怪物距离时printf输出超大错误值问题
优惠活动
大模型
产品
解决方案
定价
更多

C语言计算机器人与怪物距离时printf输出超大错误值问题

位置计算输出超大异常值的原因与修复

核心异常原因

程序输出远超合理范围的随机大数值,本质是多处C语言未定义行为共同导致的栈内存被篡改,具体错误点如下:

  • 野指针与非法输入存储:main函数中仅声明字符指针char *dir,未为其分配任何可读写的合法字符串存储空间,属于野指针;同时scanf("%s", &dir)错误对指针变量取地址,将用户输入的字符串直接写入栈上的随机内存位置,直接覆盖相邻存储的a、b变量值,这是输出超大数的最直接诱因。
  • 函数传参类型不匹配:调用findPos时传入参数为&dir(类型为char**,即字符指针的地址),但findPos的形参要求传入char*类型的字符串首地址,类型不匹配会让函数内部读取字符串时拿到完全随机的内存地址,触发未定义行为。
  • 函数名拼写错误:findPos内输出右括号时写为print(")"),C标准库不存在名为print的输出函数,未定义的函数调用会随机修改栈上的寄存器与变量值,进一步放大内存篡改的影响。
  • 缺失必要头文件:代码中使用了rand()、srand()、time()三个标准库函数,但未引入声明这些函数的<stdlib.h>、<time.h>头文件,隐式函数声明同样会导致返回值解析错误,引入随机值。

修复方案

对应每处错误做针对性调整:

  1. 将野指针替换为固定长度的字符数组,为输入的方向字符串预留合法存储空间
  2. 修正scanf的参数,直接传入数组首地址,避免多余的取地址操作;同时增加输入长度限制,防止字符串溢出
  3. 修正findPos的调用参数,传入字符串首地址与形参类型匹配
  4. 将拼写错误的print改为正确的printf
  5. 补充缺失的头文件引入

修复后的完整代码:

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

void findPos(char *dir, int a, int b)
{
    int up = 0, down = 0;
    int left = 0, right = 0;
    int i,x,y;

    for (i = 0; dir[i] != '\0' ; i++) {
        if (dir[i] == 'U' || dir[i] == 'u')
            up++;
        else if (dir[i] == 'D' || dir[i] == 'd')
            down++;
        else if (dir[i] == 'L' || dir[i] == 'l')
            left++;
        else if (dir[i] == 'R' || dir[i] == 'r')
            right++;
        else
        {
            printf("Position Unable to Find, Enter Correct Direction.");
            break;
        }
    }

    x = right - left;
    y = up - down;

    printf("Final Position of the Robot: (");
    printf("%d", x);
    printf(",%d", y);
    printf(")");

    printf("\nposition between robot and monster");
    printf("\nhorizontal: %d", a-x);
    printf("\nvertikal: %d", b-y);
}

int main()
{
    char dir[100]; // 预留100字节空间存储方向字符串
    int a,b,t;

    srand((unsigned) time(&t));
    a = rand() % 100;
    b = rand() % 100;

    printf("\nCoordinate of monster: ");
    printf("(%d,", a);
    printf("%d)", b);
    printf("\nEnter the Direction String: ");
    scanf("%99s", dir); // 直接传入数组首地址,限制输入长度避免溢出
    findPos(dir, a,b); // 直接传入字符串首地址,与形参类型匹配

    return 0;
}

修正后预期输出

以你之前的输入UURRRRRLLL、怪物坐标(5,47)为例,修正后输出为:

Coordinate of monster: (5,47)
Enter the Direction String: UURRRRRLLL
Final Position of the Robot: (2,2)
position between robot and monster
horizontal: 3
vertikal: 45

注:随机生成的怪物坐标每次运行会有变化,但距离计算结果会始终在0-100的合理范围内,不会出现超大随机值。


内容的提问来源于stack exchange,提问作者Muhammad Zikri Hr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 16:36:05