c++创建新数组导致段错误
C++ creating new array causing segfault
所以我在这个函数中有一个烦人的分段错误问题,它应该增加数组的大小。
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"进行编译,以便从您的工具中获得最大的调试帮助。
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?