pointer crash

Can some one please explain me, why the program is crashing when delete intptr and how to avoid it
1
2
3
4
5
6
7
8
9
10
11
12
13
         int aVar=10;
	int *intptr= new int; // a pointer
	cout << "intptr="<<intptr <<"\n";
	cout << "aVar="<< aVar<<"\n";
	cout<< "&aVar="<<&aVar<<"\n";
	intptr=&aVar; 
	cout <<"intptr=" <<intptr <<"\n";
	cout << "*intptr="<<*intptr <<"\n";
	*intptr=50;
	cout << "*intptr="<<*intptr <<"\n";
	cout << "aVar="<< aVar<<"\n";
	delete intptr;// deleting a pointer
Last edited on
Line 3: cout << "intptr="<<intptr <<"\n";
No value has been assigned to the pointer's allocated memory

Line 6: intptr=&aVar;
You have not freed the memory allocated by the new int before re-assigning the pointer. This is a memory leak.

Line 12: delete intptr;// deleting a pointer
The pointer is pointing to a local variable, you cannot delete a local variable. This line is the one most likely causing the crash, however the other lines are still wrong.

Last edited on
Line 12, did you mean to say, pointer is pointing to a local variable so we can not delete it?
Sorry yes. The pointer is pointing to a local variable.

Will edit that.
Got it, thank you!
line 3 is technically correct, it will just output the address of the integer that has been allocated on the heap. You cannot delete pointers that point to local variables because that is memory allocated statically by the compiler, not dynamically on the heap as a new statement does. Basically, computers have a heap that allow programs to allocate more memory to themselves when they need it, and memory allocated using new is allocated on the heap. Statically allocated memory, like local variables, live in the program memory and cannot be dealocated as the program memory is used by the program as long as it is running.

And Zaita is right line 6 will cause a memory leak, meaning the memory you allocated on the heap with new as not been deallocated meaning the operating system still think it is in use. So it there are alot of memory leaks, other programs running may crash if there isnt enough memory on the heap for them to use for their purposes. Normally with most programs this isnt a problem as they dont run for very long and fortunately when a program exits all memory program memory and dynamic memory (memory allocated on the stack) is deallocated by the operating system (and memory leaks are cleared too).
Topic archived. No new replies allowed.