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

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

问题描述

我的代码的目的是接受2个命令行参数(包括程序名),并根据给定的第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\n");
    }
    else
    {
        printf("Usage: ./caesar key\n");
    }
    
}

代码可以编译,但是出现段错误.我知道分段错误是程序试图访问为数组分配的内存之外的内容(如果我错了,请纠正我),但是我确实指定了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 通常被实现为宏,并且以这样的方式编写:如果您传递了错误的数据类型,则不会收到警告.您正在将指针传递给一个字符,该字符不是单个字符.第一个命令行参数的第一个字符是 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]))

但是最后,您想要的不是检查其中的任何数字,而是将字符串转换为整数,并查看是否发生错误-

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天全站免登陆