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
相关产品推荐
相关产品推荐

