0

Having trouble with dynamic memory allocation! How does "new int" works? What does it do?

4th Jun 2017, 9:02 AM
Stan3098
Stan3098 - avatar
6 Respostas
+ 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.
4th Jun 2017, 10:08 AM
aklex
aklex - avatar
+ 2
when we use new int() we use malloc,alloc functions to dynamically allocate memory toit
4th Jun 2017, 9:11 AM
Mayur Chaudhari
Mayur Chaudhari - avatar
+ 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.
4th Jun 2017, 9:32 AM
Haris Baig
Haris Baig - avatar
+ 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
5th Jun 2017, 3:08 AM
Andrés04_ve
Andrés04_ve - avatar
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??
4th Jun 2017, 9:15 AM
Stan3098
Stan3098 - avatar
0
Thanks ☺
4th Jun 2017, 9:52 AM
Stan3098
Stan3098 - avatar