【问题标题】:Getting a segfault- trying to retrieve data from my struct得到一个段错误——试图从我的结构中检索数据
【发布时间】:2016-04-19 04:45:23
【问题描述】:

我无法理解为什么我的代码会出现段错误。我只是想将数据存储在我的节点数组中,并想看看我的数据是否正确存储。

#define BLOCK_SIZE 256
#define MAX_NAME_LENGTH 128
#define DATA_SIZE 254
#define INDEX_SIZE 127

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

typedef enum
{
   DIR, 
   FILE, 
   INDEX,
   DATA
} NODE_TYPE;

char *bitvector; // allocate space for managing 2^16 blocks (in init)         (size is 8192)

typedef struct data_t
{
   int size;
   void *data;
} data_t;

typedef struct fs_node
{
   char name[MAX_NAME_LENGTH];
   time_t creat_t; // creation time
   time_t access_t; // last access
   time_t mod_t; // last modification
   mode_t access; // access rights for the file
   unsigned short owner; // owner ID
   unsigned short size;
   unsigned short block_ref; // reference to the data or index block
} FS_NODE;

typedef struct node
{
   NODE_TYPE type;
   union
   {
      FS_NODE fd;
  data_t data[DATA_SIZE];
  unsigned short index[INDEX_SIZE];
   } content;
} NODE;

// storage blocks
NODE *memory; // allocate 2^16 blocks (in init)

void init()
{
   memory = malloc(sizeof(NODE) * 65536);
   memory[0].type = DIR;

   FS_NODE *root = malloc(sizeof(FS_NODE));
   strcpy(root->name,"/");
   root->creat_t = 0;
   root->access_t = 0;
   root->mod_t = 0;
   root->access = 0400;
   root->owner = 0;
   root->size = 0;
   root->block_ref = 1;

   memory[0].content.fd = *root;
}

int main()
{
   printf("%s\n", memory[0].content.fd.name);
   free(memory);
   return 0;
}

【问题讨论】:

    标签: c struct segmentation-fault


    【解决方案1】:

    memory 对象在您使用之前未分配...

    改变这个

    int main() {
      printf("%s\n", memory[0].content.fd.name);
      free(memory);
      return 0;
    }
    

    到这里

    int main() {
      init();
      printf("%s\n", memory[0].content.fd.name);
      free(memory);
      return 0;
    }
    

    【讨论】:

    • 我是 ****** 我一直在通过 gbd 并没有看到任何设置大声笑...谢谢!!
    【解决方案2】:
    1. 您的 main() 函数中没有函数调用 init()。
    2. 应该有空闲内存用于 (FS_NODE *root = malloc(sizeof(FS_NODE));)。

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多