Different behavior in Visual C++ compared to MingW -


i have wrapper class int, named intwrapper, , function addn adds 2 numbers, defined follows:

intwrapper* addn(intwrapper *first, intwrapper *second) {     intwrapper c;     c.setdata(first->getdata() + second->getdata());     return &c; } 

then, in main() function this:

intwrapper first(20), second(40); intwrapper* t = addn(&first, &second); cout << (*t).getdata() << endl; 

in dev-c++(mingw32) executes intended, , print value 60, in visual c++ value -858993460.
however, if use new keyword create new object inside addn function outputs 60 in visual c++. intrigued why happens. thoughts?
full code here:

#include <iostream> using namespace std;  template<typename t, t defaultvalue> class wrapper {       private: t n_;       public:              wrapper(t n = defaultvalue) : n_(n) {}              t getdata()              {                   return n_;              }              void setdata(t n)              {                   n_ = n;              } };  typedef wrapper<int, 47> intwrapper;  intwrapper* addn(intwrapper *first, intwrapper *second) {    intwrapper c;    c.setdata(first->getdata() + second->getdata());    return &c; }  int main() {     intwrapper p;     cout << p.getdata() << endl;     intwrapper first(20), second(40);     intwrapper* t = addn(&first, &second);     cout << (*t).getdata() << endl;     system("pause");     return 1; } 

this undefined behaviour: returning pointer local variable destructed when function returns meaning return value dangling pointer.

undefined behaviour means can happen: may crash, may appear "work" correctly or may not work correctly.

when use new intwrapper instance exist beyond scope of function , not undefined behaviour , work correctly (for both vc , mingw32). remember delete returned intwrapper* when no longer required.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -