简体   繁体   English

尝试将内存分配给结构元素时收到分段错误错误

[英]Receiving segmentation fault error when trying to allocate memory to a structure element

typedef struct Node
{
    void ** pointers;
    Value ** keys;
    struct Node * parent;
    bool is_leaf;
    int num_keys;
    struct Node * next;
 } Node;

typedef struct ScanManager {
    int keyIndex;
    int totalKeys;
    Node * node;
} ScanManager;

I am getting an error "Segmentation fault (core dumped)" when I try to allocate memory for my structure ScanManager. 尝试为结构ScanManager分配内存时出现错误“分段错误(核心已转储)”。 I am writing - 我正在写 -

ScanManager * scanmeta = (ScanManager *) malloc(sizeof(ScanManager));

I have tried using calloc instead of malloc but that didn't work. 我尝试使用calloc而不是malloc但是没有用。 How do I allocate memory for that structure since I want to use it further in my code? 既然我想在代码中进一步使用它,该如何为该结构分配内存?

typedef struct Value {
  DataType dt;
  union v {
    int intV;
    char *stringV;
    float floatV;
    bool boolV;
  } v;
} Value;

Also, I have one more structure - 另外,我还有一个结构-

typedef struct BT_ScanHandle {
    BTreeHandle *tree;
    void *mgmtData;
} BT_ScanHandle;

I am passing this structure's reference in a function as mentioned below and try to access my ScanManager structure here - 我正在通过下面提到的函数传递此结构的引用,并尝试在此处访问我的ScanManager结构-

openTreeScan(BT_ScanHandle **handle)
{
    struct ScanManager *scanmeta = malloc (sizeof (struct ScanManager));
    (** handle).mgmtData = scanmeta;

    /* Remaining code */
}

I finally figured out the error. 我终于发现了错误。 It was not in allocating space to ScanManager . 它不是在分配空间给ScanManager Instead, I was trying to initialize some of the members of BT_ScanHandle structure without allocating memory space to itself. 相反,我试图初始化BT_ScanHandle结构的某些成员, BT_ScanHandle分配内存空间。 The working code is - 工作代码是-

openTreeScan(BT_ScanHandle **handle)
{
    struct ScanManager *scanmeta = malloc(sizeof(ScanManager));
    *handle = malloc(sizeof(BT_ScanHandle)); //Allocating some space
    (*handle)->mgmtData = scanmeta; // Initializing

    /* Remaining code */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM