Re: [Dev-C++] Crash with macro to template conversion
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2004-02-27 15:18:59
|
First of all - your create template function is declared to return void,
so why do you end it with return ptr?
Second, you send in a T* ptr parameter. Note that since C++ uses
call-by-value, this will behave like a lokal variable, i.e any assign to
ptr will not reflect back to the caller. You should change the first
parameter of create to be a reference to a pointer. That way, the assign
to ptr will reflect back to the variable obj of the caller.
/Per W
On Fri, 27 Feb 2004, David McKen wrote:
> Ok here is my problem.
>
> I want to replace:
> #define CREATE(result, type, number) \
> do \
> { \
> if (!((result) = (type *) calloc ((number), sizeof(type)))) \
> { \
> perror("malloc failure"); \
> fprintf(stderr, "Malloc failure @ %s:%d\n", __FILE__, __LINE__ );
> \
> abort(); \
> } \
> } while(0)
>
> With it's C++ equivalent.
>
> So far I have:
> #define CREATE(result, type, num) = create<type>((result),(num))
> template<class T>
> void create(T * ptr, int number, char * f_name = __FILE__, int l_num
> =
> __LINE__)
> {
> try {
> ptr = new T[number];
> }
> catch(bad_alloc& b)
> {
> perror("malloc failure");
> fprintf( stderr, "Malloc failure @ %s:%d\n", f_name, l_num );
> abort();
> }
> if ( !ptr )
> {
> perror("malloc failure");
> fprintf( stderr, "Malloc failure @ %s:%d\n", f_name, l_num );
> abort();
> }
> return ptr;
> }
>
> But the program crashes after the function call when any attempt to
> acces
> the data occours:
> e.g.
> OBJ_DATA * obj;
> CREATE( obj , OBJ_DATA, 1 );
>
> obj->some_field = 5; //Crashes here and obj = 0x0 from gdb.
>
> Thanks in Advance
> David McKen
>
>
> __________________________________
> Do you Yahoo!?
> Get better spam protection with Yahoo! Mail.
> http://antispam.yahoo.com/tools
>
>
> -------------------------------------------------------
> SF.Net is sponsored by: Speed Start Your Linux Apps Now.
> Build and deploy apps & Web services for Linux with
> a free DVD software kit from IBM. Click Now!
> http://ads.osdn.com/?ad_id=1356&alloc_id=3438&op=click
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|