相关疑难解决方法(0)

可以在其范围之外访问局部变量的内存吗?

我有以下代码.

#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

怎么会这样?本地变量的内存不能在其功能之外无法访问吗?

c++ memory-management local-variables dangling-pointer

990
推荐指数
19
解决办法
26万
查看次数

什么是悬垂指针?

我知道这是很常见的问题,但对我来说还是新的!

我不明白悬挂指针的概念,谷歌搜索,并编写测试方法找到一个.

我只是想知道这是一个悬垂的指针吗?无论我发现什么样的东西都回来了,我在这里尝试类似的东西!

谢谢!

void foo(const std::string name)
{
    // will it be Dangling pointer?!, with comments/Answer
    // it could be if in new_foo, I store name into Global.
    // Why?! And what is safe then?
    new_foo(name.c_str());
}

void new_foo(const char* name)
{
    // print name or do something with name...   
}
Run Code Online (Sandbox Code Playgroud)

c++ pointers dangling-pointer

43
推荐指数
5
解决办法
5万
查看次数

C++ delete - 删除我的对象,但我仍然可以访问数据?

我写了一个简单的,工作的俄罗斯方块游戏,每个块作为类单块的一个实例.

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++ pointers c++-faq undefined-behavior

30
推荐指数
5
解决办法
1万
查看次数