0

我对 C/C++ 中的指针世界很陌生,所以这对你来说可能是一个很简单的问题:

以下 C++ 代码正常工作

#include <iostream>

int main()
{
    int theInt = 1337;
    int & theReference = theInt;
    int * thePointer = &theInt;

    std::cout << "int: " << theInt << "\n";
    std::cout << "referenz: " << theReference << "\n";
    std::cout << "pointer: " << *thePointer << "\n";
    std::cout << "pointer: " << *thePointer << "\n";

    //std::cout << "foo" << "\n";

    return 0;
}

但更换时停止工作

//std::cout << "foo" << "\n";

std::cout << "foo" << "\n";

.

我所说的“停止工作”是指:“被我的诺顿安全系统阻止为潜在威胁”(如果有任何帮助,将导致返回代码“0x76F531AF”)。由于诺顿通常不会干扰我的编程,我假设在 cout 中双重使用 int 指针会以某种方式导致段错误......

谢谢你的帮助!

PS:

我在 Windows 8.1 上使用 Code::Blocks 和来自 TDM-GCC(版本 4.7.1,32 位)的 GCC 编译器和 GDB 调试器。

编辑:删除指针的删除 - >问题仍然存在。

4

2 回答 2

0

You can only delete objects created on the heap (using new or C-style malloc and such).

// allocate on the heap
int *intOnTheHeap = new int;

// do some stuff with it
*intOnTheHeap = 0;
(*intOnTheHeap)++;
std::cout << *intOnTheHeap << std::endl;

// deallocate
delete intOnTheHeap;

If you take a pointer to a local variable, it will point to an entry on the stack. You don't need to and shouldn't deallocate that memory yourself. The memory is "freed" by changing the stackpointer automatically when your variable runs out of scope (at the end of the function).

void myFunction() {
    int localVariable;
    int *pointerToLocalVariable = &localVariable;

    // forbidden and unnecessary:
    //delete pointerToLocalVariable;

    // here (end of the block) the memory on the stack
    // will be freed automatically
}
于 2015-09-21T09:15:50.027 回答
0

由于我在完全不同的上下文中在 Norton-Interception 之后遇到了同样的错误,这似乎是 Code::Blocks Norton 不兼容的情况。

于 2015-09-22T10:00:57.303 回答