c++创建新数组导致段错误

C++ creating new array causing segfault

本文关键字:错误 段错误 数组 创建 新数组 c++      更新时间:2023-10-16

所以我在这个函数中有一个烦人的分段错误问题,它应该增加数组的大小。

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

我认为这可能是一个大小问题(#成员vs字面值大小的字节),所以我尝试:

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

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

下面是Node和Argument的定义
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 - 0 -g"进行编译,以便从您的工具中获得最大的调试帮助。