c++ c++-faq copy-constructor assignment-operator rule-of-three
我有以下代码.
#include <iostream>
int * foo()
{
int a = 5;
return &a;
}
int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)
而代码只是运行而没有运行时异常!
输出是 58
怎么会这样?本地变量的内存不能在其功能之外无法访问吗?
我想知道如何malloc
和free
工作.
int main() {
unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
memset(p,0,4);
strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes**
cout << p;
free(p); // Obvious Crash, but I need how it works and why crash.
cout << p;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果答案在记忆水平上是深入的,如果可能的话,我将非常感激.
我写了一个简单的,工作的俄罗斯方块游戏,每个块作为类单块的一个实例.
class SingleBlock
{
public:
SingleBlock(int, int);
~SingleBlock();
int x;
int y;
SingleBlock *next;
};
class MultiBlock
{
public:
MultiBlock(int, int);
SingleBlock *c, *d, *e, *f;
};
SingleBlock::SingleBlock(int a, int b)
{
x = a;
y = b;
}
SingleBlock::~SingleBlock()
{
x = 222;
}
MultiBlock::MultiBlock(int a, int b)
{
c = new SingleBlock (a,b);
d = c->next = new SingleBlock (a+10,b);
e = d->next = new SingleBlock (a+20,b);
f = e->next = new SingleBlock (a+30,b);
}
Run Code Online (Sandbox Code Playgroud)
我有一个扫描完整行的函数,并运行删除相关的块的链接列表并重新分配 - >下一个指针. …
我这里有一个非常简单的C++代码:
char *s = new char[100];
strcpy(s, "HELLO");
delete [] s;
int n = strlen(s);
Run Code Online (Sandbox Code Playgroud)
如果我通过按F5(开始调试)从Visual C++ 2008运行此代码,这总是导致崩溃(访问冲突.)但是,在IDE外部启动此可执行文件,或使用IDE的Ctrl + F5(启动而不调试)不会'导致任何崩溃.有什么区别?
我还想知道是否可以稳定地重现因访问已删除区域而导致的访问冲突崩溃?现实生活中这种崩溃难得一见吗?
我用GCC 5.2(C++ 11)测试了以下代码:
#include <iostream>
#include <memory>
struct Foo
{
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
void bar() { std::cout << "Foo::bar\n"; }
};
void f(const Foo &)
{
std::cout << "f(const Foo&)\n";
}
int main()
{
std::unique_ptr<Foo> p1(new Foo); // p1 owns Foo
if (p1) p1->bar();
{
//p1->bar();
std::unique_ptr<Foo> p2(std::move(p1)); // now p2 owns Foo
f(*p2);
p1->bar();
if(p1==nullptr)
{
std::cout<<"NULL"<<std::endl;
}
p1 = std::move(p2); // ownership returns to p1
std::unique_ptr<Foo> p3;
p3->bar();
std::cout …
Run Code Online (Sandbox Code Playgroud)