0
Having trouble with dynamic memory allocation! How does "new int" works? What does it do?
6 Answers
+ 6
Calling delete doesnt mean the value at that pointer will actually be deleted. It just gives the memory back to the OS to be used for other processes. That doesnt always mean the OS will give it to another process right away, nor that its value will be changed right away either. It depends on the OS and the context. However, after deleting memory on the heap, you should never deference that pointer, as it will cause undefined bahvior.
+ 2
when we use new int() we use malloc,alloc functions to dynamically allocate memory toit
+ 2
new int basically reserve memory for int so the *ptr gets a memory where it can save a value of int. Simple int have their own reserved memory which is reserved at the time of their creation but *ptr does not have(so that we can point it to other memory location or variable) and that's why we use new.
+ 2
new finds memory equal to the size of an integer (4 bytes, but it could change)
int *x; is a variable that points to a memory address with an integer
x = new int; assigns x the address of a memory space found by new
*x = 5; puts the value 5 in the address that x have
delete x; the memory got now is free
0
void main()
{
int *p=new int;
*p=5;
cout<<*p;
}
In this output would be same even if new int wasn't present . So what does it do? We even can delete the pointer but still if we take an output i will get 5. So what does "delete" actually deleted??
0
Thanks âș