【问题标题】:using int pointer in multiple couts在多个 couts 中使用 int 指针
【发布时间】:2015-09-21 09:08:47
【问题描述】:

我对 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 调试器。

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

【问题讨论】:

  • delete thePointer 仅在您使用int *thePointer = new int 时才需要,因此请删除它
  • 我删除了那行,问题依旧。
  • 您是否正在运行旧版本的输出二进制文件?您是否检查了发布/调试配置等?您的 IDE 是否有“干净”命令?我问这个是因为在您删除 delete thePointer 后您的代码没有任何问题。
  • “被我的诺顿安全系统阻止为潜在威胁”因为这意味着“为什么软件 X 是垃圾”,这确实是一个话题。你希望我们告诉你什么?您已经知道您拥有的特定 Norton Security 安装是无用的垃圾。您可以忍受疼痛并继续使用它,或者摆脱它。您的选择。
  • @KubaOber 实际上,我认为诺顿的干预是指针误入歧途的标志,所以它并不是真正的:“为什么诺顿不能正常工作”。

标签: c++ pointers segmentation-fault cout norton


【解决方案1】:

您只能在堆上创建delete 对象(使用new 或C 风格的malloc 等)。

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

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

// deallocate
delete intOnTheHeap;

如果你把一个指针指向一个局部变量,它将指向堆栈上的一个条目。您不需要也不应该自己释放该内存。当变量超出范围时(在函数末尾),通过自动更改堆栈指针来“释放”内存。

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
}

【讨论】:

  • 谢谢!我更改了这部分,但问题仍然存在。
  • @MtDoom 我不了解诺顿,但除了delete,您的代码非常好。当然没有任何分段错误。
  • 看起来诺顿是这里唯一真正的问题。我应该更改问题的标志和标题,还是只是将我自己的答案(“都是诺顿的错”)标记为解决方案而不做更多的事情?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多