MtDoom
MtDoom

Reputation: 1

using int pointer in multiple couts

I'm quite new to the world of pointers in C/C++ so this may be quite an easy question for you:

The following C++-Code works normally

#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;
}

but stops working when changing

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

to

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

.

By "stops working" I mean: "is blocked by my norton security as a potential threat" (resulting in a return code of "0x76F531AF" if this is any help). Since norton normally doesn't interfere withe my programming I assume the double use of the int pointer in cout somehow results in a segfault...

Thx for your help!

PS:

I use Code::Blocks on Windows 8.1 with the GCC compiler and GDB debugger from TDM-GCC (version 4.7.1, 32 bit).

EDIT: removed deletion of pointer -> problem remains.

Upvotes: 0

Views: 81

Answers (2)

MtDoom
MtDoom

Reputation: 1

Since I got the same error after Norton-Interception in totally different contexts, this seems to be a case of Code::Blocks Norton incompatibility.

Upvotes: 0

mastov
mastov

Reputation: 2982

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
}

Upvotes: 0

Related Questions