C中的分段错误,无法解释原因

问题描述 投票:0回答:2

我有一个应该读取(以非常糟糕的方式)文件的函数。我希望它能修改我作为参数传递的结构,以存储它必须读取的内容。但是当我调用它时,它会引发分段错误。我有一个打印作为该功能的第一件事,它没有这样做。所以我想我的函数声明有问题。我无法弄清楚。

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);

但它仍然显示我的分段错误。

c core fault
2个回答
0
投票

这是一个工作示例:

#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(或包括标题等)s.t.当你在main中调用它时,编译器知道签名。

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

运行main后的输出是:

Hello
config.data = 12

0
投票

当你声明任何变量,指针或没有,而不初始化它,它获取内存中的任何内容作为其当前值。某些更高级别的语言可能会使用“默认”变量隐式初始化所有新值。您可能已经习惯了以前的编程经验;这不是C的情况。

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

你需要初始化指针指向某个东西;要么是现有的struct client_config,要么是用malloccalloc分配的新堆内存。

另外,如果你的函数真的是要指向struct client_config,那么参数也应该有一个*操作符。

© www.soinside.com 2019 - 2024. All rights reserved.