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

C语言矩阵框架中访问指针致矩阵元素异常变更问题排查

问题根源:内存分配不足导致的堆内存越界

你的问题出在内存分配时没有考虑float类型的字节大小,导致堆内存越界写入,意外覆盖了原矩阵a的内存空间。

具体问题点

看你的matrix_create和matrix_init函数:

a->numbers = (float *) malloc (lines * columns);

这里你只分配了lines * columns个字节,但每个float元素在大多数系统上占4个字节。实际需要的内存大小应该是lines * columns * sizeof(float),当前分配的内存只有实际需求的1/4,后续写入矩阵元素时必然会越界,破坏堆上相邻的其他内存区域——刚好你的矩阵a的内存就在answer的旁边,所以被意外修改了。

为什么注释掉matrix_init就正常?

当你注释掉matrix_init时,answer->numbers是未初始化的野指针,但此时没有实际往answer里写入数据(或者说越界写入的行为没影响到a的内存),所以a的元素看起来正常。但这只是巧合,这种写法属于严重错误,会导致未定义行为,绝对不能作为解决方案。

修复方案

修改matrix_create和matrix_init中的malloc语句,补充sizeof(float)来计算正确的内存大小:

修改后的matrix_create

void matrix_create (Matrix * a, const float *array, int lines, int columns) {
 a->numbers = (float *) malloc (lines * columns * sizeof(float)); // 乘以sizeof(float)
 a->lines = lines;
 a->columns = columns;
 for (int i = 0; i < a->lines; i++)
 for (int j = 0; j < a->columns; j++)
 *(a->numbers + j + i * columns) = *(array + j + i * columns);
}

修改后的matrix_init

void matrix_init (Matrix * a, int lines, int columns) {
 a->numbers = (float *) malloc (lines * columns * sizeof(float)); // 乘以sizeof(float)
 a->lines = lines;
 a->columns = columns;
}

验证结果

修复后运行代码,输出会恢复正常:

1.000000 2.000000 3.000000 
4.000000 5.000000 6.000000 
7.000000 8.000000 9.000000 
10.000000 11.000000 12.000000 

1.000000 2.000000 3.000000 
4.000000 5.000000 6.000000 
7.000000 8.000000 9.000000 
10.000000 11.000000 12.000000 

3.000000 6.000000 9.000000 
12.000000 15.000000 18.000000 
21.000000 24.000000 27.000000 
30.000000 33.000000 36.000000 

另外,建议你补充内存释放函数避免内存泄漏:

void matrix_destroy(Matrix *a) {
    free(a->numbers);
    a->numbers = NULL;
    a->lines = 0;
    a->columns = 0;
}

在main函数结束前调用matrix_destroy(&a);和matrix_destroy(&b);即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:25:48