locket23 locket23 - 1 year ago 76
C++ Question

c++ random numbers when returning pointer from function

I have the following code in C++ . Everytime I run it ,it has a different output. Why does this happen ? Is it somehow related to memory leak ?

#include <iostream>

using namespace std;
template <class T, class U>
T f(T x, U y)
return x+y;
int f(int x, int y)
return x-y;
int main()
int *a=new int(4), b(16);
return 0;

Answer Source

You are passing a pointer and a normal int to f, because

int *a=new int(4), b(16);

works like

int *a=new int(4);
int b(16);

Thus, in f, you have T == int* and U == int, then you add the int to the pointer and return the resulting pointer. As it does not point to memory you own and initialized, dereferencing it is UB and may yield garbage or crash or do whatever it likes.

As I already said in the comments, you should not try to learn C++ by trial and error, that really will not work, believe me. Learn it systematically from a good book instead. You will see that there is no need to use pointers for this in the first place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download