【问题标题】:Segfault when giving a function a struct pointer给函数一个结构指针时的段错误
【发布时间】:2021-09-18 13:17:04
【问题描述】:

我有一个看起来像这样的函数:

int lexWhitespace(TokenizerOutput* input) {

    printf("he");
    if (!(14 > input->toStillParse[0] > 8) && !(input->toStillParse[0] == 32)) {
        // checks if the first character in the toStillParse section of input is whitespace.
        return -1;
    } else {input->tokenizerOutput[0] = input->toStillParse[0];}



    for (int i = 1; ; i++) {
        if ((14 > input->toStillParse[0] > 8) || (input->toStillParse[0] == 32)) {
        // checks if the first character in the toStillParse section of input is whitespace.
            input->tokenizerOutput[i] = input->toStillParse[i];
        } else {return 0;}
    }
}

接受这个结构:

struct TokenizerOutput {
    const char* toStillParse; // holds the text that still needs to be parsed.
    char* tokenizerOutput; // holds the text that was just output by tokenizer function.
};
typedef struct TokenizerOutput TokenizerOutput;

当我尝试像这样在主函数中调用它时:

int main(void) {
    printf("hello\n");

    TokenizerOutput j = {"        k", " "};

    printf("%s\n", (&j)->toStillParse);

    lexWhitespace(&j);

    return 0;
}

我得到一个段错误。段错误发生在函数 lexWhitespace 甚至运行任何东西之前,因为它不打印“he”。我不知道为什么会这样。任何帮助将不胜感激。我正在使用 gcc 9.3.0。

【问题讨论】:

  • 字符串文字通常不可写。 char *x = " "; x[0] = 'a'; 会出现同样的错误
  • printf("he");更改为printf("he\n"); fflush(stdout);

标签: c gcc c99 gcc9


【解决方案1】:

这段代码有一些错误。

首先,这个条件:

14 > input->toStillParse[0] > 8

这可能是无意的。应该是这样写的:

14 > input->toStillParse[0] && input->toStillParse[0] > 8

第二,这个循环可能永远不会终止:

for (int i = 1; ; i++) {
    if ((14 > input->toStillParse[0] > 8) || (input->toStillParse[0] == 32)) {
    // checks if the first character in the toStillParse section of input is whitespace.
        input->tokenizerOutput[i] = input->toStillParse[i];
    } else {return 0;}
}

请注意,被比较的字符toStillParse[0] 在每次循环迭代中都是同一个字符。所以这个循环要么立即退出,要么永远循环(并且可能崩溃/段错误)。看起来[0] 应该是[i]。另请注意,条件可能写错了。

在 C 中,x > y > zx > y && y > z 不同。每当您看到x > y > z 时,都可能是错误的(除非您正在查看 IOCCC 条目或其他内容)。

【讨论】:

  • 这很有趣。还没到那部分。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多