繁体   English   中英

为什么strlen会导致C中的分段错误?

[英]Why is strlen causing a segmentation fault in C?

(警告)是的,这是我正在做的作业的一部分,但是我现在非常绝望,不,我不是在找你们为我解决它,但是任何提示将不胜感激!(/警告)

我正在尝试制作一个交互式菜单,用户应输入一个表达式(例如“ 5 3 +”),并且程序应检测到它的后缀表示法,很遗憾,我遇到了分段错误错误,我怀疑它们与strlen函数的使用有关。

编辑:我能够使其工作,首先char expression[25] = {NULL}; 线
成为char expression[25] = {'\\0'};

并调用时determine_notation函数I除去[25]从我传递像这样的阵列: determine_notation(expression, expr_length);

同样,我将input[length]部分更改为input[length-2]因为就像前面的评论中提到的那样, input[length] == '\\0'input[length--] == '\\n'

总而言之,感谢您的帮助!

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

int determine_notation(char input[25], int length);

int main(void)
{
    char expression[25] = {NULL}; // Initializing character array to NULL
    int notation;
    int expr_length;

    printf("Please enter your expression to detect and convert it's notation: ");
    fgets( expression, 25, stdin );

    expr_length = strlen(expression[25]); // Determining size of array input until the NULL terminator
    notation = determine_notation( expression[25], expr_length ); 
    printf("%d\n", notation);
}

int determine_notation(char input[25], int length) // Determines notation
{

    if(isdigit(input[0]) == 0)
    {
        printf("This is a prefix expression\n");
        return 0;
    }
    else if(isdigit(input[length]) == 0)
    {
        printf("This is a postfix expression\n");
        return 1;
    }
    else
    {
        printf("This is an infix expression\n");
        return 2;
    }
}

您可能会得到警告,说明您在此调用中将char转换为指针:

expr_length = strlen(expression[25]);
//                             ^^^^

这是问题所在-您的代码引用了数组末尾不存在的元素(未定义的行为),并尝试将其传递给strlen

由于strlen需要一个指向字符串开头的指针,因此调用需要

expr_length = strlen(expression); // Determining size of array input until the NULL terminator

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM