包含字符串数组的结构的malloc问题
malloc issue with struct of containing an array of strings
我已经阅读了关于这个问题的其他帖子。当我更改顶部行时:
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)。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 如果没有malloc,链表实现将失败
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Malloc 在使用线程并行化 SSH 调用时存在问题
- 将 C 代码移植到C++,将 void* 从 malloc 转换为所需指针的问题
- C++自动内存 malloc 和免费覆盖问题
- OpenCL代码的malloc问题-OS X上mach_vm_map的巨大大小
- 包含字符串数组的结构的malloc问题
- 尝试处理嵌套对象/结构和动态数组时出现内存泄漏或内存错误。可能的 Xcode/malloc 问题
- allocc函数崩溃,但malloc没有问题