memcpy中的EXC_BAD访问

时间:2013-02-07 14:25:18

标签: c exc-bad-access memcpy

我尝试构建BST并在其中插入节点。但是,在创建新节点时,我不断收到exc_bad访问错误。可能是什么原因?这是我的代码:

struct Node *node_create(struct BSTree *bst,void *nodeKey, struct Value *nodeVal, struct     Node *rightChild, struct Node *leftChild)
{
struct Node *node = malloc(sizeof *node);
nodeKey= malloc (sizeof (bst->key_size));
nodeVal = malloc(sizeof(bst->value_size));
size_t sizeKey = sizeof(nodeKey);
memcpy(node->key, nodeKey, sizeKey);  // exc_bad access
size_t sizeVal = sizeof (nodeVal);
memcpy(node->val, nodeVal, sizeVal); // exc_bad access
node->right = rightChild;  
node->left = leftChild;

return node;

}

struct Node {
void *key;
struct Value *val;
struct Node *left;
struct Node *right;
};



struct BSTree {
size_t key_size, key_alignment;
size_t value_size, value_alignment;
int (*compare_func)(void *, void *);
struct Node *root;
// ... Maybe some other stuff.
};

struct Value {
char name[10];
int id;
};

2 个答案:

答案 0 :(得分:2)

在不知道Node的情况下,我会说,即使你已经分配了node,你还没有分配所有成员(看起来像是指针)。 / p>

将您的代码更改为:

// Allocate node
struct Node *node = malloc(sizeof *node);
// Now members
node->key = malloc (sizeof (bst->key_size)); 
// :

如果您传递了键和值,请将这些值的memcpy执行到上述位置。但如果没有进一步的代码,很难说...

答案 1 :(得分:0)

不看Node节点,我猜你想做的是:

如果节点定义为

struct Node {
    void *key;
    struct Value *val;
    struct Node *right;
    struct Node *left;
};

然后

struct Node *node_create(struct BSTree *bst,void *nodeKey, struct Value *nodeVal, struct     Node *rightChild, struct Node *leftChild)
{
struct Node *node = malloc(sizeof *node);

  node->key = malloc(bst->key_size);          /* No sizeof here */
  node->val = malloc(bst->value_size);
  memcpy(node->key, nodeKey, bst->key_size);  
  memcpy(node->val, nodeVal, bst->value_size);
  node->right = rightChild;  
  node->left = leftChild;

  return node;
}

由于您没有检查malloc的返回(这是一个可以证明合理的设计选择),您甚至可以用这种方式更简单地编写它。

struct Node *node_create(struct BSTree *bst,void *nodeKey, struct Value *nodeVal, struct     Node *rightChild, struct Node *leftChild)
{
struct Node *node = malloc(sizeof *node);

  node->key = memcpy(malloc(bst->key_size)  , nodeKey, bst->key_size); 
  node->val = memcpy(malloc(bst->value_size), nodeVal, bst->value_size);
  node->right = rightChild;  
  node->left = leftChild;
  return node;
}

有些人对这种风格感到畏缩,但我不想在裁员方面过多地淡化我的代码。