包含字符串数组的结构的malloc问题

malloc issue with struct of containing an array of strings

本文关键字:malloc 问题 结构 包含 数组 字符串      更新时间:2023-10-16

我已经阅读了关于这个问题的其他帖子。当我更改顶部行时:

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;
}

可以进行哪些小的修改来消除内存访问错误?

类可以使用运算符new而不是malloc创建。使用字符串成员时,需要进行

p = new Node_type();

而不是

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

运算符new初始化字符串的内部内存。malloc函数,而不是。

您没有为字符串调用构造函数。此外,养成编写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)。