Thursday, July 9, 2009

Help with c/c++?

I have a project in which I have to answer what is wrong with these pieces of code? I am new to C/C++ (know Java)





Q:





struct MyStruct


{


int *p;


MyStruct(int n) { p = new int; *p = n; }


~MyStruct() { delete p; }


};





------------------------------...


Q:





int *array(int n)


{


return new int(n);


}





int main()


{


int *p = array(10);


for( int i = 0; i %26lt; 10; i++ )


{


p[i] = 0;


}


printf( "%d\n", p[0] );


p = array(10);


printf( "%d\n", p[0] );


return 0;


}








------------------------------...


Q:








class A { public: int a, b; };


class B


{


public:


const A a;


B() :a() { }


};





int main()


{


B b;


printf( "%d %d\n", b.a.a, b.a.b );


return 0;


}





I would like some help on these please.





Thanks,

Help with c/c++?
#1 - should be a class instead of a struct. structs can't have methods defined.





#2 - should be new int [ n ] instead of new int ( n ) - as it is, it allocates one int with value of n, rather than n ints.





#3 - Class A's constructor is not defined.
Reply:Question 1:





The implementation is stupid, but correct. It is wasteful to allocate a int dynamically.





Also, in VC6 the code would be bad because the return from operator new wasn't checked for NULL. VC7 and up conform to the C++ standard which requires new to throw on bad alloc.





Question 2:





This code leaks memory. The allocated arrays are never deleted. Also, the second printf will output a "random" value.





Question 3:





A::a and A::b are never initialized.


No comments:

Post a Comment