如何识别导致分段错误的原因 [英] How to identify what is causing the Segmentation fault

查看:16
本文介绍了如何识别导致分段错误的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码的目标是接收 2 个命令行参数(包括程序名称),并根据给定的第二个命令行参数打印出如图所示的响应.如果命令行参数是一个整数,则用户的输入被接受或成功",如果它是其他任何东西(例如,一个字符串或多个命令行参数),它将为 Null 并且将显示错误消息.这是为熟悉的人准备的CS50凯撒

My code's aim is to take in 2 command line arguments (inclusive of programme name), and to print out responses as shown based on the given 2nd command line argument. If the command line argument is an integer, the user's input is accepted or "Success"and if it as anything else (e.g. a string or more than one command line argument), it will be Null and the error message will be shown. This is for CS50 caesar for those who are familiar

我的代码如下:

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

int main(int argc,string argv[])
{
 
    char *x = argv[1];
    if (argc == 2 && isdigit(x))
    {
        printf("Success
");
    }
    else
    {
        printf("Usage: ./caesar key
");
    }
    
}

代码可以编译,但出现分段错误.我知道分段错误是程序试图访问为数组分配的内存之外的东西(如果我错了,请纠正我)但我确实指定了 argv[1].

The code compiles but I am given a segmentation fault. I am aware segmentation fault is the programme trying to access something outside of the allocated memory for the array (correct me if I am wrong) but I did specify argv[1].

推荐答案

isdigit 接受一个参数,一个 int,它包含作为无符号字符的字符代码.

The isdigit takes as an argument, an int, that contains a character code as an unsigned character.

不幸的是,isdigit 通常被实现为宏,并且以这样一种方式编写,即如果您传入错误类型的数据,您不会收到警告.您将 pointer 传递给一个字符,该字符不是单个字符.第一个命令行参数的第一个字符是 x[0].然而这个必须被转换成unsigned char.

Unfortunately isdigit is often implemented as a macro, and written in such a way that you do not get a warning if you pass in the wrong kind of data. You're passing in a pointer to a character, which is not a single character. The first character of the first command line argument is x[0]. However this must be converted to unsigned char.

所以这些都是错误的

  • isdigit(x)

isdigit(x[0])

你可以用来检查第一个参数的第一个字符是否是数字

What you could use to check if the first character of the first argument is a digit is

isdigit((unsigned char)x[0]))

但最终你想要的不是检查其中任何一个是否为数字,而是将字符串转换为整数,看看是否出现错误 - x使用strto(u)l,看看是否成功;然后检查结果值的范围.

but in the end what you want is not to check if any of these are digits, but to convert the string to an integer, and see if an error occurs - use strto(u)l for x and see if it succeeded; then check the range of the resulting value.

这篇关于如何识别导致分段错误的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆