簡體   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;

嘗試為結構ScanManager分配內存時出現錯誤“分段錯誤(核心已轉儲)”。 我正在寫 -

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

我嘗試使用calloc而不是malloc但是沒有用。 既然我想在代碼中進一步使用它,該如何為該結構分配內存?

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

另外,我還有一個結構-

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

我正在通過下面提到的函數傳遞此結構的引用,並嘗試在此處訪問我的ScanManager結構-

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

    /* Remaining code */
}

我終於發現了錯誤。 它不是在分配空間給ScanManager 相反,我試圖初始化BT_ScanHandle結構的某些成員, BT_ScanHandle分配內存空間。 工作代碼是-

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