C 中的分段错误,不知道为什么

Segmentation fault in C, can't figure why

我有一个函数应该读取(以一种非常糟糕的方式)文件。我希望它修改我作为参数传递的结构,以存储它必须读取的内容。但是当我调用它时,它会引发分段错误。我有一个 print 作为函数做的第一件事,但它没有做。所以我想我对函数声明或其他东西有疑问。想不通了。

int main(int argc, char **argv){
    //some parser here
    struct client_config *config;
    read_software_config_file(*config); //I also passed it as non pointer and & but nothing worked.
    } 

void read_software_config_file(struct client_config config){
    printf("Hello"); //it breaks here
  }

正如有人指出我这样做的:

 struct client_config config;
 read_software_config_file(&config);

但它仍然显示分段错误。

这是一个工作示例:

#include <stdio.h>

struct client_config
{
    int data;
};

void read_software_config_file(struct client_config *config); // Forward Declaration

int main(int argc, char **argv)
{
    struct client_config config; // Memory on stack. Use malloc/calloc for heap
    config.data = 10; // Init data
    read_software_config_file(&config);
    printf("config.data = %d\n", config.data);

    return 0;
}

void read_software_config_file(struct client_config *config)
{
    printf("Hello\n");
    config->data = 12;
}

我通常建议使用 -Wall -Wextra -pedantic 进行编译以尽早发现错误。

您必须转发声明函数 read_software_config_file(或包括 header 等)s.t。当您在 main 中调用它时,编译器知道签名。

如评论中所述,您应该使用指向结构的指针,s.t。可以修改。

运行 main 之后的输出是:

Hello
config.data = 12

当您声明任何变量(无论是否为指针)而不对其进行初始化时,它会获取内存中的任何内容作为其当前值。某些高级语言可能会使用 "default" 变量隐式初始化所有新值。您可能已经从以前的编程经验中习惯了这一点; C 中不是这种情况。

如果您在未初始化的指针上使用 * 解引用运算符,您将解引用指针当前值表示的任何地址,这是未定义的行为,几乎肯定会导致访问冲突.

您需要初始化您的指针以指向某物;现有的 struct client_config,或分配有 malloccalloc.

的新堆内存

此外,如果您的函数确实需要一个指向 struct client_config 的指针,则该参数也应该有一个 * 运算符。