You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言考拉兹猜想程序运行报Thread 1: EXC_BAD_ACCESS错误如何解决

问题排查与修复方案
  • 核心报错原因:空指针访问
    你代码中直接调用atoi(argv[1])读取命令行传入的初始数值,但没有提前校验命令行参数数量。如果运行程序时没有传入参数,argv[1]就是空指针,atoi访问0地址就会触发你遇到的EXC_BAD_ACCESS (code=1, address=0x0)错误。
    补充说明:你代码用fork()创建的是子进程而非线程,你描述中的“首个线程”属于表述误差。

  • 其他潜在问题

  1. 缺失wait()函数对应的头文件<sys/wait.h>,部分编译环境下会触发隐式声明错误,运行时可能出现异常
  2. Collatz函数中输入非法的提示字符串存在拼写错误,postive应为positive,且输出后未加换行,容易和后续打印内容混排
修复后完整代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h> // 补全wait所需头文件

int Collatz(int num)
{
    int count = 0;

    if(num <= 0)
    {
        printf("<Starting Value> should be positive integer\n"); // 修复拼写+加换行
        return 0;
    }
    while(count != 10000)
    {
        if(num == 1)
        {
            printf("%i ",num);
            return 0;
        }
        else if(num % 2 == 0)
        {
            printf("%i ",num);
            num /= 2;
        }
        else
        {
            printf("%i ",num);
            num = num * 3 + 1;
        }
        count++;
    }
    return 0;
}
int main(int argc, char *argv[])
{
    // 新增参数校验
    if (argc != 2) {
        printf("Usage: %s <positive integer>\n", argv[0]);
        return 1;
    }
    int num, stat_loc = 0;
    pid_t pid;
    num = atoi(argv[1]);

    pid = fork();

    if(pid == -1)
    {
        printf("Child process didnt get created.\n");
    }
    else if(pid == 0)
    {
        printf(": ");
        Collatz(num);
    }
    else if(pid > 0)
    {
        wait(&stat_loc);
        printf("\n");
    }
    return 0;
}
测试方法

编译后运行时需要传入正整数参数即可正常执行,示例运行命令:
./编译后的可执行文件名 15

内容的提问来源于stack exchange,提问作者Bam19

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:18:02