This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: throw <const string>


>     char* buf = "Memory allocation failure!";
>     try
>     {
>            throw "Memory allocation failure!";
>           //  throw buf;
>     }
>     catch( char *str)
>     {
>         cout << "Exception raised: " << str << '\n';
>     }



A string literal in a throw statement is not converted to a char*.  For the
|throw "Memory allocation failure";|, you have to |catch(const char*)| for
this to work properly.  On the other hand, your |buf| variable is a char*,
because it is declared that way.  Hence, the |catch(char*)| works just fine
in the |throw buf;| case.

> 
>  If I compile this code and execute it gives me
> segmentation fault.


I guess I am also a little surprised it gives a seg fault.  


> 
> 
>  What I can n't understand is both buf and Memory
> Allocation are pointers. (point to read only data.).


|buf| is not read only.  You have to declare it that way.  

	const char* buf = "Memory allocation failure!";

You may want to consider using the standard library exceptions.

--Matt


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]