C++创建导致段错误的新数组

标签 c++ arrays class memory segmentation-fault

所以我在这个函数中遇到了一个恼人的段错误问题,它应该会增加数组的大小。

void Node::pushArg(Argument arg)
{
    Argument * newlist = new Argument[argc+1];
    for (int i = 0; i < argc; i++)
        newlist[i] = args[i];
    newlist[argc] = arg;
    delete[] args;
    args = newlist;
    argc++;
}

当我在使用 gdb 时运行它,它告诉我我的段错误是由这一行引起的:

Argument * newlist = new Argument[argc+1];

我认为这可能是大小调整的问题(成员数量与以字节为单位的文字大小)所以我尝试了:

Argument * newlist = new Argument[sizeof(Argument)*(argc+1)]

但这也会以完全相同的方式导致段错误。帮忙?

如果有帮助:这是节点和参数的定义

class Argument
{
public:
    bool nested; // is the Argument a string, or a nested Node?
    char * str_content; // string value
    Node * nested_node; // Pointer to nested note

    Argument(); // Null intializer
    Argument(char *); // Create string node 
    Argument(Node *); // Create nested node
    Argument(const Argument&); // Copy constructor
};

class Node
{
public:
    char * head; // Head of list (function)

    int argc; // # of arguments
    Argument * args;

    Node(); //intialize null
    Node(char *); // intialize with head

    void pushArg(Argument); // Add an argument to list

    char * toString(); // the Node in String Format
};

最佳答案

鉴于“argc”是一个成员值,段错误很可能是由于“this”是一个无效值,可能是 NULL。你可以通过这样做来检查

void Node::pushArg(Argument arg)
{
    size_t numArgs = argc + 1;

然后在该行出现段错误时查看“this”的值。

您可能还应该使用“-Wall -Wextra -O0 -g”进行编译,以便从您的工具中获得最大程度的调试帮助。

关于C++创建导致段错误的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884366/

相关文章:

c++ - 创建窗口和线程 - C++

c++ - 像数组一样构造 std::string

c - 将 char 数组传递给采用 char 指针的函数

ios - 如何在 Swift 中按数字和字母顺序对数组进行排序

c# - 如何在 C# 中每 3 项用逗号将数组连接到字符串

c++ - 函数模板不起作用,出现错误 "No suitable user-defined conversion"

C++ 等价于 StringBuffer/StringBuilder?

java - 访问 ArrayList 中的特定元素

python - 对一个对象执行某些操作会对同一类的所有对象执行相同的操作吗?

python - 如何设置字典值使其表现得像实例属性?