【发布时间】:2017-04-19 22:13:04
【问题描述】:
最近我在删除一个对象时会抛出一个异常,我已将其范围缩小到使用 strcpy()。为了测试这一点,我做了一个简单的测试类,它(基本上)只使用 strcpy() 和瞧,一个例外。
#pragma once
class TestClass
{
public:
TestClass(char []);
~TestClass();
char teststring[];
};
它的构造函数是这样的:
TestClass::TestClass(char incstring[])
{
strcpy(teststring, incstring);
printf(teststring);
}
如果我运行以下代码:
int main(){
TestClass* test = new TestClass("Cheezit");
delete test;
}
我得到一个抛出的异常! STRCPY() 发生了什么??!?!?!?!
注意:控制台窗口会打印“Cheezit”。
【问题讨论】:
-
这不是一个有效的类定义。您的代码不是有效的 C++;使用损坏的编译器(或以损坏的方式使用编译器)很不幸,它可以让您逃脱惩罚。
-
请编辑您的问题以包含minimal reproducible example
-
@Slava:它被称为“flexible array member”。您只能在动态分配上下文中使用它。
-
该代码不是 MCVE,因为它缺少所需的
#includes 和~TestClass的定义。 -
不能在 gcc ideone.com/Z1JY2J上编译
标签: c++ exception memory strcpy