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

C语言模拟类调用方法触发Segmentation fault问题排查请求

C语言模拟类时Segmentation fault错误排查

问题代码

头文件test2d.h

#include <stdio.h>

struct test2d {
    int a, b;
    int (*add)(struct test2d c);
};

extern const struct test2dClass {
    struct test2d (*new)(int a, int b);
} test2d;

主程序代码

#include <math.h>
#include "test2d.h"

static int add(struct test2d c) {
    return 'f';
}

static struct test2d new(int a, int b) {
    return (struct test2d){ .a = a, .b = b };
}

const struct test2dClass test2d = { .new = &new };

int main(int argc, char argv[]) {
    struct test2d c = test2d.new(23, 4);
    printf("valeur a : %d, b: %d\n", c.a, c.b);
    printf("%d\n dfsd", c.add(c));
}

错误原因

  • 函数指针未初始化:创建struct test2d实例时,仅初始化了a和b成员,未给add函数指针赋值。c.add此时是野指针,调用时会访问非法内存,直接触发Segmentation fault。
  • main函数参数不规范:main的第二个参数应为char *argv[]或char **argv,当前写法char argv[]不符合C标准,存在潜在风险。

修复方案

修改new函数初始化add指针,同时修正main函数参数:

#include <math.h>
#include "test2d.h"

static int add(struct test2d c) {
    return 'f';
}

static struct test2d new(int a, int b) {
    // 初始化add函数指针
    return (struct test2d){ .a = a, .b = b, .add = add };
}

const struct test2dClass test2d = { .new = &new };

// 修正main参数格式
int main(int argc, char *argv[]) {
    struct test2d c = test2d.new(23, 4);
    printf("valeur a : %d, b: %d\n", c.a, c.b);
    printf("%d\n dfsd", c.add(c));
}

修复后运行会输出:

valeur a : 23, b: 4
102
 dfsd

(注:'f'的ASCII值为102,因此输出102)

内容的提问来源于stack exchange,提问作者Loïc Lavo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:20:25