【问题标题】:Why do I ge a segmentation Fault when I run this function? [closed]为什么我在运行此功能时会出现分段错误? [关闭]
【发布时间】:2018-01-22 22:22:01
【问题描述】:

为什么我在发送标志 -h 或 -H 时会出现分段错误。

bool parse_command(int argc, char **argv, bool *header, char **fileName)
{

    if (!argv)
        return false;

    bool *flagh = false;
    bool *flagH = false;

    char *options = "Hh";
    int opt = 0;

    while ( (opt = getopt(argc, argv, options ) ) != -1)
    {
        printf("HELLO");
        switch (opt)
        {
            case 'h': 
                *flagh = true; 
                break;
            case 'H':
                *flagH = true; 
                break;
            default:
                usage_p1();  
                return false;
        }

    }
    printf("%d", opt);
    // Implement this function
    return true;
}

【问题讨论】:

  • booltrue 不是 C 中的关键字。您使用的是 C++ 编译器吗?
  • flagh 前面的星号表明它是一个指针 - 你没有分配。
  • 这甚至不能编译,或者至少没有警告。 flagh 和 flagH 是指向布尔值的指针,但它们不指向任何东西。您在内存中没有任何实际的布尔值。然后将它们(指针)分配给“false”,这实际上使它们指向内存地址 0,因此是段错误。
  • 您定义了两个指针变量,但您对它们的初始化并没有使它们指向有效位置。在我看来,这些变量应该是指针。
  • @klutt 但是,它们在stdbool.h中定义

标签: c segmentation-fault flags getopt


【解决方案1】:

这两行是你的问题:

bool *flagh = false;
bool *flagH = false;

您将flaghflagH 声明为布尔值的指针,但它们还没有指向任何地方。事实上,它们绝对没有指向任何地方,因为您的初始化相当于

bool *flagh = NULL;
bool *flagH = NULL;

您可能不希望这些成为指针。将声明更改为

bool flagh = false;
bool flagH = false;

将分配更改为

flagh = true; 

flagH = true; 

【讨论】:

    【解决方案2】:

    看看这个:

    bool *flagh = false;
    bool *flagH = false;
    

    两个变量都是指针,你用false初始化它们。没有 truefalse 在 C 中,而不是当它被认为是 false 计算结果为 0,当它不是 false 时,将被视为 true

    如果这是真正的 C 代码,那么它和做的一样

    bool *flagh = NULL;
    bool *flagH = NULL;
    

    以后再做

    *flagh = true;
    

    正在取消引用 NULL 指针,该指针未定义,将导致 段错误。

    修复您的代码:

    #include <stdbool.h>
    
    bool flagh = false;
    bool flagH = false;
    

    然后迟到

    flagh = true;
    flagH = true;
    
    // or
    
    flagh = false;
    flagH = false;
    

    就像许多人在 cmets 中所说的那样,C 没有真正的布尔类型。见:Using boolean values in C

    编辑

    现在有 stdbool.h 声明一个类型 booltruefalse,但所做的只是将 true 重新定义为 1,将 false 重新定义为 0:

    stdbool.h

    #ifndef _STDBOOL_H
    #define _STDBOOL_H
    
    #ifndef __cplusplus
    
    #define bool  _Bool
    #define true  1
    #define false 0
    
    #else /* __cplusplus */
    
    /* Supporting _Bool in C++ is a GCC extension.  */
    #define _Bool bool
    
    #if __cplusplus < 201103L
    /* Defining these macros in C++98 is a GCC extension.  */
    #define bool  bool
    #define false false
    #define true  true
    #endif
    
    #endif /* __cplusplus */
    
    /* Signal that all the definitions are present.  */
    #define __bool_true_false_are_defined 1
    
    #endif    /* stdbool.h */
    

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-01-07
      相关资源
      最近更新 更多