c++ - using int pointer in multiple couts -


i'm quite new world of pointers in c/c++ may quite easy question 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" mean: "is blocked norton security potential threat" (resulting in return code of "0x76f531af" if help). since norton doesn't interfere withe programming assume double use of int pointer in cout somehow results in segfault...

thx help!

ps:

i use code::blocks on windows 8.1 gcc compiler , gdb debugger tdm-gcc (version 4.7.1, 32 bit).

edit: removed deletion of pointer -> problem remains.

you can delete objects created on heap (using new or c-style malloc , such).

// allocate on heap int *intontheheap = new int;  // stuff *intontheheap = 0; (*intontheheap)++; std::cout << *intontheheap << std::endl;  // deallocate delete intontheheap; 

if take pointer local variable, point entry on stack. don't need , shouldn't deallocate memory yourself. memory "freed" changing stackpointer automatically when variable runs out of scope (at end of function).

void myfunction() {     int localvariable;     int *pointertolocalvariable = &localvariable;      // forbidden , unnecessary:     //delete pointertolocalvariable;      // here (end of block) memory on stack     // freed automatically } 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -