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

C语言图像模糊函数触发Segmentation fault问题排查求助

段错误原因排查与修复

1. 循环变量增量错误(直接触发段错误)

代码里有两处循环增量写错,直接导致循环变量异常增长,最终超出数组下标范围触发越界:

  • 遍历列的外层循环,增量写成了w++,正确应为j++:
    // 错误写法
    for (int j = 0; j < width; w++)
    // 修正后
    for (int j = 0; j < width; j++)
    
  • 遍历邻域列的内层循环,增量写成了j++,正确应为w++:
    // 错误写法
    for (int w = j - 1; w <= j + 1; j++)
    // 修正后
    for (int w = j - 1; w <= j + 1; w++)
    

2. 边界判断逻辑错误

C语言不支持0 <= h < height这类连续比较写法,实际执行时会先计算0 <= h得到0或1,再用该结果与height比较,导致错误判定下标合法性(比如h=-1时会被误判为合法),进而访问越界元素:

// 错误写法
if (0 <= h < height && 0 <= w < width)
// 修正后
if (h >= 0 && h < height && w >= 0 && w < width)

3. 累加变量溢出问题(非段错误直接原因,但需修复)

sumRed、sumGreen、sumBlue使用BYTE(uint8_t)类型,而3x3邻域最多9个像素,每个RGB值最大255,累加值最大为9*255=2295,远超过uint8_t的最大值255,会导致溢出计算错误。需改为int类型:

// 错误写法
BYTE sumRed, sumGreen, sumBlue;
// 修正后
int sumRed, sumGreen, sumBlue;

修正后的完整函数示例

void blur(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE new_image[height][width];
    int sumRed, sumGreen, sumBlue;
    int numPixels;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            sumRed = sumGreen = sumBlue = 0;
            numPixels = 0;
            for (int h = i - 1; h <= i + 1; h++)
            {
                for (int w = j - 1; w <= j + 1; w++)
                {
                    if (h >= 0 && h < height && w >= 0 && w < width)
                    {
                        sumRed += image[h][w].rgbtRed;
                        sumGreen += image[h][w].rgbtGreen;
                        sumBlue += image[h][w].rgbtBlue;
                        numPixels++;
                    }
                }
            }

            new_image[i][j].rgbtRed = (BYTE)(sumRed / numPixels);
            new_image[i][j].rgbtGreen = (BYTE)(sumGreen / numPixels);
            new_image[i][j].rgbtBlue = (BYTE)(sumBlue / numPixels);
        }
    }

    memcpy(&image[0][0], &new_image[0][0], sizeof(image[0][0]) * height * width);
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:45:35