I wrote the following piece of code
#include <iostream>
using namespace std;
void temp (int * x)
{
x=new int [2];
x[0]=1;
x[1]=2;
}
int main()
{
int *ptr;
temp(ptr);
cout<<ptr[0]<<endl;
cout<<ptr[1]<<endl;
return 0;
}
Running it gives seg fault, so is the memory allocation which happens inside temp function local to function? The memory gets deallocated while returning from temp? I know, that to solve this problem, I need to pass pointer to pointer ptr, but still, why exactly does this thing not work?
<iostream>,using namespace std,new,std::cout,operator <<andstd::endlmean that your program is C++ rather than Cnewordeleteoperators at all. Only STL containers and smart pointers.delete[]new. I'd agree aboutdelete; at least in C++11,std::unique_ptrandstd::shared_ptreffectively automate deletion. But you still have to initialize them somehow.