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

时间:2015-12-02 06:48:45

标签: c pointers memory-management struct malloc

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分配内存时,我收到错误“Segmentation fault(core dumped)”。我在写 -

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 */
}

1 个答案:

答案 0 :(得分:1)

我终于找到了错误。它不是在为ScanManager分配空间。相反,我试图初始化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 */
}