【问题标题】:why am i getting this segmentation fault when trying to access a struct using a pointer?为什么在尝试使用指针访问结构时出现此分段错误?
【发布时间】:2020-12-12 06:21:22
【问题描述】:

我正在尝试学习嵌套结构。当我使用结构变量访问它时,它工作正常。 但是当我尝试使用指针访问它时,它会显示分段错误。

#include <stdio.h>
#include <stdlib.h>

struct Vehicle {
    int eng;
    int weight;
};

struct Driver {
    int id;
    float rating;
    struct Vehicle v;
};

void main() {
    struct Driver *d1;
    d1->id = 123456;
    d1->rating = 4.9;
    d1->v.eng = 456789;

    printf("%d\n", d1->id);
    printf("%f\n", d1->rating);
    printf("%d\n", d1->v.eng);
}

【问题讨论】:

  • 由于您没有为结构驱动程序分配内存,因此出现分段错误!您可以在堆栈上分配内存(通过声明驱动程序,struct Driver d; struct Driver* pd=&amp;d;)或通过调用malloc 在堆上分配内存。 struct Driver* pd = malloc(sizeof(struct Driver));

标签: c struct segmentation-fault gdb


【解决方案1】:

在取消引用之前,您必须初始化指向有效缓冲区地址的指针。

例如:

void main(){
    struct Driver d; /* add this */
    struct Driver *d1;
    d1 = &d; /* add this */

另外我建议您在托管环境中使用标准int main(void) 而不是void main(),这在C89 中是非法的,在C99 或更高版本中是由实现定义的,除非您有特殊原因使用非标准签名。

【讨论】:

    【解决方案2】:

    您需要先初始化指针,然后才能访问它所指向的内容。这是修复它的一种方法:

        struct Driver data;
        struct Driver *d1 = &data;
        d1->id=123456;
        d1->rating=4.9;
        d1->v.eng=456789;
    
        printf("%d\n",d1->id);
        printf("%f\n",d1->rating);
        printf("%d\n",d1->v.eng);
    

    注意data的添加,以及d1的初始化指向它。运行时,它会产生:

    123456
    4.900000
    456789
    

    另一种初始化它的方法是通过malloc 使用动态分配的内存,在这种情况下,您稍后将释放您分配的内存。

    【讨论】:

      【解决方案3】:

      你使用了指针d1,但没有初始化它。

      你需要先初始化它,例如malloc:

      struct Driver *d1 = malloc(sizeof(struct Driver));
      
      if(NULL == d1)
      {
          perror("can't allocate memory");
          exit(1);
      }
      
      // ... using d1
      
      free(d1);
      return 0;
      

      【讨论】:

      • 您应该检查malloc() 返回值并调用free()。请将此添加到您的答案中。
      猜你喜欢
      • 2016-05-05
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2016-02-23
      • 2021-06-21
      • 1970-01-01
      相关资源
      最近更新 更多