C:
language support: No
library support: <stdlib.h> ==> malloc(), calloc(), realloc(), free() ==> heap
C++:
language support: new, delete ==> heap (best option)
library support: <cstdlib> ==> malloc(), calloc(), realloc(), free() ==> heap
int main()
{
if (true)
{
int x = 5;
}
// x now out of scope, memory it used to occupy can be reused
}
#include <iostream>
using namespace std;
int main()
{
int *p;
if (true)
{
int x = 5;
p = &x;
}
cout << *p << endl; // ??? (dangling pointer)
}
Implement a function which returns a pointer to some memory containing the integer 5
Incorrect implementation:
#include <iostream>
using namespace std;
int* getPtrToFive()
{
int x = 5;
return &x;
}
int main()
{
int *p = getPtrToFive();
cout << *p << endl; // ??? (dangling pointer)
}
int *x = new int;
// use memory allocated by new
delete x;
Implement a function which returns a pointer to some memory containing the integer 5
correct implementation:
#include <iostream>
using namespace std;
int *getPtrToFive()
{
int *x = new int;
*x = 5;
return x;
}
int main()
{
int *p = getPtrToFive();
cout << *p << endl; // 5
delete p;
}