【问题标题】:C++ creating new array causing segfaultC ++创建导致段错误的新数组
【发布时间】:2013-06-02 15:39:59
【问题描述】:

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

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 的值是多少?你能构造一个minimal test-case吗?
  • argc在Node的所有构造函数中初始化为0
  • 使用 '-g' 编译,并在 argc (p argc) 出现段错误的地方发布值。你有什么理由不使用 std::vector 吗?
  • 是的,我想我将转向 std::vector,虽然我最初没有这样做,因为我被要求尽可能使用数组

标签: c++ arrays class memory segmentation-fault


【解决方案1】:

鉴于“argc”是一个成员值,段错误很可能是由“this”是一个无效值引起的,可能是NULL。您可以通过以下方式进行检查

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

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

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

【讨论】:

  • 很好的调用,问题是节点没有复制构造函数,所以当我使用 push_back() 将节点添加到我的堆栈时,argc 丢失了,当我尝试创建数组时导致段错误大小 > 40 亿:P(或 -0249240356 随便选)
猜你喜欢
  • 1970-01-01
  • 2018-02-13
  • 2017-02-25
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多