包含字符串数组的struct的malloc问题

时间:2015-04-09 20:24:36

标签: c++ string malloc

我已阅读有关此问题的其他帖子。当我改变顶线时:

typedef char Key_type;

typedef string Key_type;

我在p->key[1] = x;

时收到内存访问错误
typedef char Key_type; // change this to string and it breaks
typedef struct node_tag{
    int count;
    Key_type key[maxSize + 1];
    struct node_tag *branch[maxSize + 1];
}Node_type;

Node_type *Insert(Key_type newkey, Node_type *root)
{
    Key_type x; /* node to be reinserted as new root    */
    Node_type *xr;  /* subtree on right of x        */
    Node_type *p;   /* pointer for temporary use        */
    Bool pushup; /* Has the height of the tree increased? */

    pushup = PushDown(newkey, root, &x, &xr);
    if (pushup) {   /* Tree grows in height.*/
        /* Make a new root: */
        p = (Node_type *)malloc(sizeof(Node_type));
        p->count = 1;
        p->key[1] = x; // memory access error
        p->branch[0] = root;
        p->branch[1] = xr;
        return p;
    }
    return root;
}

可以做些什么小修改来消除内存访问错误?

2 个答案:

答案 0 :(得分:1)

可以使用operator new而不是malloc创建

类。使用字符串成员时,您需要执行

p = new Node_type();

而不是

p = (Node_type *)malloc(sizeof(Node_type));

operator new初始化字符串的内部存储器。 malloc函数,不是。

答案 1 :(得分:0)

你没有为你的字符串调用构造函数。另外,养成编写C ++而不是C:

的习惯
typedef string Key_type;
struct Node_type{ // don't need to do typedef ...
    int count;
    Key_type key[maxSize + 1];
    Node_type *branch[maxSize + 1];
};

Node_type *Insert(Key_type newkey, Node_type *root)
{
    Key_type x; /* node to be reinserted as new root    */
    Node_type *xr;  /* subtree on right of x        */
    Node_type *p;   /* pointer for temporary use        */
    Bool pushup; /* Has the height of the tree increased? */

    pushup = PushDown(newkey, root, &x, &xr);
    if (pushup) {   /* Tree grows in height.*/
        /* Make a new root: */
        p = new Node_type;
        p->count = 1;
        p->key[1] = x; // memory access error
        p->branch[0] = root;
        p->branch[1] = xr;
        return p;
    }
    return root;
}

如果您没有为结构提供ctor,编译器将为您创建一个(以及dtor)。