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

运行行星判断C程序时出现Segmentation Fault的原因排查

问题描述

现有一个C程序,功能是接收命令行传入的行星名称参数,判断并打印该参数是否为行星。当输入正常大小写的行星名(如./planets Venus Mercury)时运行正常,但输入包含小写名称的参数(如./planets Venus Mercury mercury)时,会出现Segmentation Fault(段错误)。附程序代码如下:

#include <stdio.h>
#include <string.h>

#define NUM_PLANETS 9

int main(int argc, char* argv[]) {
    char *planets[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Pluto" };
    int i, j;
    for (i = 1; i < argc; i++) {
        for (j = 0; j < NUM_PLANETS; j++) {
            if (strcmp(argv[i], planets[j]) == 0) {
                printf("%s is planet %d\n", argv[i], j + 1);
                break;
            }
        }
        if (j == NUM_PLANETS) {
            printf("%s is not a planet\n", argv[i]);
        }
    }
}
段错误原因

核心问题是数组越界访问:

  • 代码中NUM_PLANETS被定义为9,但planets数组实际只初始化了8个元素(从Mercury到Pluto共8个行星)。
  • 当输入的参数(比如小写的mercury)和所有8个行星名都不匹配时,内层循环的j会一直递增到9——因为循环条件是j < NUM_PLANETS(即j < 9),当j=8时仍会执行一次循环,尝试访问planets[8]。
  • 但planets数组的有效索引范围是0到7,访问planets[8]属于越界操作,会读取数组之后的未知内存区域。这块内存可能是无效地址,当strcmp尝试读取该地址的内容时,就会触发段错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:22:10