调用isalpha导致分段错误 [英] Calling isalpha Causing Segmentation Fault

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

问题描述

我有以下引起分段错误的程序.

I have the following program that causes a segmentation fault.

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

int main(int argc, char *argv[])
{
    printf("TEST");

    for (int k=0; k<(strlen(argv[1])); k++)
    {
        if (!isalpha(argv[1])) {
            printf("Enter only alphabets!");
            return 1;
        }
    }

    return 0;
}

我发现是这条线引起了问题

I've figured out that it is this line that is causing the problem

if (!isalpha(argv[1])) {

并用argv[1][k]替换argv[1]解决了该问题.

and replacing argv[1] with argv[1][k] solves the problem.

但是,我很奇怪该程序导致分段错误,甚至没有打印TEST.我还希望isalpha函数错误地检查指向argv[1]char*指针的低字节,但是事实并非如此.我有代码来检查参数的数量,但为了简洁起见,这里没有显示.

However, I find it rather curious that the program results in a segmentation fault without even printing TEST. I also expect the isalpha function to incorrectly check if the lower byte of the char* pointer to argv[1], but this doesn't seem to be the case. I have code to check for the number of arguments but isn't shown here for brevity.

这是怎么回事?

推荐答案

通常,讨论为什么未定义的行为导致此结果或其他结果是毫无意义的.

In general it is rather pointless to discuss why undefined behaviour leads to this result or the other.

但是尝试理解为什么发生某些事情即使在规范之外也是没有害处的.

But maybe it doesn't harm to try to understand why something happens even if it is outside the spec.

isalpha的实现使用简单的数组查找所有可能的unsigned char值.在这种情况下,作为参数传递的值将用作数组的索引. 虽然实字符限制为8位,但整数不是. 该函数将int作为参数.这也是为了允许输入EOF,而这又不适合unsigned char.

There are implementation of isalpha which use a simple array to lookup all possible unsigned char values. In that case the value passed as parameter is used as index into the array. While a real character is limited to 8 bits, an integer is not. The function takes an int as parameter. This is to allow entering EOF as well which does not fit into unsigned char.

如果将0x7239482342之类的地址传递到函数中,则该地址将远远超出所述数组的末尾,并且当CPU尝试读取具有该索引的条目时,它将掉入世界的边缘. ;)

If you pass an address like 0x7239482342 into your function this is far beyond the end of the said array and when the CPU tries to read the entry with that index it falls off the rim of the world. ;)

使用这样的地址调用isalpha是编译器应发出有关将指针转换为整数的警告的地方.你可能会忽略...

Calling isalpha with such an address is the place where the compiler should raise some warning about converting a pointer to an integer. Which you probably ignore...

可能包含用于检查有效参数的代码,但它也可能仅依赖于用户未传递不应传递的内容.

The library might contain code that checks for valid parameters but it might also just rely on the user not passing things that shall not be passed.

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

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