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

t检验代码出现段错误,无法定位非法内存使用位置求排查

t检验程序段错误原因排查

核心错误点:

  • input函数返回逻辑完全错误
    函数声明返回int,但实际返回的是栈上局部数组x的地址(隐式转为int)。栈上局部变量在函数执行结束后会被销毁,返回的地址属于无效内存。后续把这个无效地址存在int类型的a、b中,再当作浮点数组指针传入mean、sumsq函数时,会直接访问非法内存,触发段错误。另外input函数的参数n缺少类型声明,不符合标准C语法,应改为int input(int n)。

  • 变量类型不匹配
    在t_diff_of_means中,a、b被声明为int,但它们需要存储浮点数组的地址,正确类型应该是float*。用int存储指针地址会导致地址被截断(64位系统下必然出错),进一步加剧非法内存访问。

  • 未定义行为:函数未返回值
    t_diff_of_means声明返回float,但函数末尾没有return语句,这会导致未定义行为,虽不是直接触发段错误的原因,但也是必须修复的问题。


关键代码修正示例:

  1. 修改input函数为动态分配内存:
#include <stdlib.h> // 需要引入malloc、exit的头文件

float* input(int n)
{
    float *x = malloc(n * sizeof(float));
    if (x == NULL) {
        printf("内存分配失败");
        exit(1);
    }
    printf("Enter the values one by one: ");
    for (int i = 0; i < n; i++)
        scanf("%f", &x[i]);
    return x;
}
  1. 修改t_diff_of_means中的变量声明及内存释放:
float t_diff_of_means()
{
    float x=0.0,y=0.0,s1=0.0,s2=0.0,S=0.0,t=0.0;
    int n,m;
    float *a, *b; // 改为float*类型
    printf("Enter the number of variables in population 1: ");
    scanf("%d", &n);
    a = input(n);
    printf("Enter the number of variables in population 2: ");
    scanf("%d", &m);
    b = input(m);
    x = mean(a,n);
    y = mean(b,m);
    s1 = sumsq(a, n);
    s2 = sumsq(b, m);
    S  = sqrt((s1+s2)/(n+m-2));
    t = fabs(x-y)/(S*sqrt(1.0/n+1.0/m)); // 增加fabs取绝对值,符合t检验逻辑
    t_check(t);
    
    // 释放动态分配的内存,避免内存泄漏
    free(a);
    free(b);
    return t; // 补上返回值
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:05:28