[英]C++ Memory Allocation new[] and delete[]
I'm trying to dynamically allocate a new object.我正在尝试动态分配一个新的 object。
int len = (nm == NULL) ? 0 : strlen(nm);
try {
name = new char[len + 1];
}
catch(std::bad_alloc) {
name = NULL;
}
if(name) {
if(nm == NULL)
strcpy(name, "");
else
{
strcpy(name, nm);
cmds=new command [num_of_cmds];
Then my destructor has them being deleted via然后我的析构函数通过删除它们
robot::~robot()
{
if (name) {
delete[] name;
}
delete [] cmds;
}
I keep getting segementation faults, if i edit some code to initialize a value on a simple int, it breaks.我不断遇到分段错误,如果我编辑一些代码以在简单的 int 上初始化一个值,它就会中断。 My delete[] cmds breaks so i have to comment it out.
我的 delete[] cmds 坏了所以我必须把它注释掉。 Any help would be greatly appreciated.
任何帮助将不胜感激。 I will clarify more things if people need.
如果人们需要,我会澄清更多的事情。
When your robot' name is NULL ( nm == NULL
), you alloc an empty string, but don't alloc cmds
.当您的机器人名称为 NULL (
nm == NULL
) 时,您分配一个空字符串,但不分配cmds
。 So you should at least set cmds to NULL in that branch, or check in destructor if (name && *name != 0)
before delete [] cmds;
因此,您至少应该在该分支中将 cmds 设置为 NULL,或者在
delete [] cmds;
之前检查析构函数if (name && *name != 0)
; . . I'd go with the first option...
我会选择第一个选项 go ...
Unless you have a very good reason not to, you should avoid using new[]
and delete[]
and instead use std::string
and std::vector
.除非你有充分的理由不这样做,否则你应该避免使用
new[]
和delete[]
而是使用std::string
和std::vector
。 These handle memory management for you;这些为您办理memory管理; and are considerable easier to use because of that.
并且因此更容易使用。
std::vector
is far more useful than a manually allocated buffer, not only because it handles memory for you, but it is still compatible with older C-style APIs. std::vector
比手动分配的缓冲区有用得多,不仅因为它为您处理 memory,而且它仍然与旧的 C 风格 API 兼容。 In situations where you need to provide a const char *
or char *
, you can simply provide &vec[0]
(as in, the address of the first element of the std::vector
).在需要提供
const char *
或char *
的情况下,您可以简单地提供&vec[0]
(例如, std::vector
的第一个元素的地址)。
std::string
makes memory management, string manipulation, and (in conjunction with std::stringstream
) string formatting much, much, much easier. std::string
使 memory 管理、字符串操作和(与std::stringstream
结合)字符串格式化变得非常非常容易。 Don't be tempted to deal with memory management yourself, use the well-tested std::string
and std::vector
.不要试图自己处理 memory 管理,使用经过充分测试的
std::string
和std::vector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.