Hello i am currently learning about the heap memory or the free store, and was wondering in what situations do you need use dynamic allocation? I understand what it is but not how it is needed.
And how do i know how much memory my program uses and how can i know how much memory available?
Can someone please give me an example, maybe in a piece of code. thanks
in what situations do you need use dynamic allocation?
1) you do not know how much data you will get.
2) You do not want to store things on stack. (Usually space issues)
3) You want to benefit from polymorphism. (You can do this with stack allocated mmory, but it is not pretty)
#include <iostream>
usingnamespace std;
int* func();
int main(){
int* i=newint{0};
cout<<"i before: "<<*i;
delete i;
i=func();
cout<<"i after func: "<<*i<<" mem address: "<<i;
*i=99;
cout<<"i is modifying int on the heap created by func."<<endl<<"i is: "<<*i;
delete i;
return 0;
}
int* func(){
int* heap_int=newint{9878};
cout<<"heap_int in func"<<*heap_int<<" mem address: "<<heap_int;
return heap_int;
}
#include <iostream>
#include <new>
int func(void)
{
int a = 1; int b = 2; int c=3; int d=4; int e=5;
int five = 55;
int* the_heap = &five;
return *the_heap;
}
void funk(void)
{
int myInt = func();
std::cout << myInt << std::endl;
}
int main()
{
funk();
}
intfunc() //Returns by value
{
int a = 1; int b = 2; int c=3; int d=4; int e=5;
int five = 55; //Declaring a variable
int* the_heap = &five; //Saving pointer to it
return *the_heap; //Getting value by this pointer and copy-return it
} //the_heap is destroyed here, but we already copied its value
You do copy address. But now it points to nonexisting variable
1 2 3 4 5 6 7 8 9 10 11 12
double* child(void)
{
double dLocalVariable; //Createing variable
return &dLocalVariable; //REturning pointer to it
} //dLocalVariable is destoyed. All pointers to it (including returned one) are invalid
void parent(void)
{
double* pdLocal;
pdLocal = child(); //child() returns invalid pointer
*pdLocal = 1.0; //Undefined behavior: We are trying to write to the nonexisting variable
}