c++ random numbers when returning pointer from fun

2019-09-29 17:34发布

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);
    cout<<*f(a,b);
    return 0;
}

标签: c++ oop
1条回答
2楼-- · 2019-09-29 18:11

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.

查看更多
登录 后发表回答