I created a simple project just to test how deleting variable works but i encountered a strange thing... I created three int variables (1 stack based and 2 heap based) and when i deleted the heap variables using delete i still could access them. I can print them or change their value but how? Isn't delete supposed to permanently delete the variable from memory and also another question.... Why stack based variables can't be deleted using free() or delete?
Here is the (C++) script -
#include<iostream>
using namespace std;
void Stuff()
{
int* heap_int = (int*)malloc(4); //Heap based variable
*heap_int = 500;
int stack_int = 5; //Stack based variable
int* calloc_int = (int*)calloc(1,2); //Heap based variable
*calloc_int = 600;
std::cout << "Value (HeapInt) : " << *heap_int << "\n"; //Prints 500
std::cout << "Value (CallocInt) : " << *calloc_int << "\n"; //Prints 600
std::cout << "Value (StackInt) : " << stack_int << "\n"; //Prints 5
delete heap_int;
delete calloc_int;
//delete stack_int; (will not work)
std::cout << "\nValue after delete (HeapInt) : " << *heap_int << "\n"; //Still prints 500
std::cout << "Value after delete (CallocInt) : " << *calloc_int << "\n"; //Still Prints 600
std::cout << "Value after delete (StackInt) : " << stack_int << std::endl; //Prints 5
*heap_int = 82;
}
int main()
{
Stuff();
}
I heard in online tutorials that heap based variables only get freed if we used delete or free() (unlike stack variables who get freed automatically when their scope ends) then why can't i access an heap based variable out of scope like this...?
#include<iostream>
void Function()
{
int* variable = new int;
*variable = 6;
}
int main()
{
*variable = 9; //Error says "Use of Undeclared identifier variable"
}