+ 2

Why the program is crushing !!??

#include<iostream> using namespace std; int main() { int *ptr; *ptr=5; cout<<*ptr; return 0; } The programming is crushing when ran in code::Blocks 16.01 it's an integer pointer which takes 4 bytes of memory. the value "5" should have got assigned in it and give output . Rather , the program is chushing.

22nd May 2018, 9:56 AM
Nieb Hasan
Nieb Hasan - avatar
4 Answers
+ 4
int* ptr = new int; ptr will point to a rubbish adress without this assignment. The new keyword is there to actually say: I want memory for a new variable. And it returns the new variables adress. Note that you must delete ptr; by hand to return its underlying memory. ptr itself is not deleted, it just points to a deleted variable. int a; is different. a doesn't need new and it's deleted when it goes out of {scope}. Use scope deletion whereever possible. It's faster and safer.
22nd May 2018, 1:32 PM
Timon PaƟlick
+ 3
pointers should hold the address of other variables. try this: int main(){ int *ptr, a; a = 5; ptr = &a; cout << *ptr; return 0; }
22nd May 2018, 10:12 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 2
How does a program crush? And what is it crushing?
22nd May 2018, 12:37 PM
Paul Grasser
Paul Grasser - avatar
0
By program crush , i mean runtime error
22nd May 2018, 1:28 PM
Nieb Hasan
Nieb Hasan - avatar