Hi Group,
When i compile the following program it compiles successfully, but
crashes while executing.
Be happy. Undefined behavior can be much worse than that, for
example it could crash every time somebody else runs the program,
but never when you run it. (Such behavior isn't unheard of, and
can be pretty tricky to track down).
I am trying to assign a NULL char pointer to a
string.
I really don't understand why you post here when you know what you
do wrong.
The error message is
/home1/murugan/prog/ccprog >./a.out
Abort(coredump)
/home1/murugan/prog/ccprog >
Looks like a unix like system... If you are lucky there might be
a file named core, a.out.core or something similar that you could
use to debug your program.
The program is :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string request;
This line creates an empty string with automatic storage.
This line creates a pointer to char, initializing it to NULL, that
is it doesn't point anywhere.
This line calls the version of the assignment operator of std::string
that takes a const char* argument, which creates a new string object,
by calling the version of the constructor that takes a const char*
argument, and then assigns that new string to request.
In the constructor string::string(const char* s) the argument 's'
must be a valid pointer to a memory region containing a zero-
terminated string. NULL is not such a value, so you have
undefined behavior, and from here anything could happen, Crashing
immediatly is most common on modern platforms where NULL points
to unmapped memory, but be careful, you can't count on that...
cout<<endl<<request<<endl;
If you had removed NULL assignment above, this line would print
two newlines, since request is empty after it's default constructor.
I find '\n' clearer than std::endl, so personally I would have said:
cout << '\n' << request << '\n'; But that is mostly a matter of taste,
there are some subtle differences between the two versions, but they
rarely matter.
Portable return values from main are 0, EXIT_SUCCESS and EXIT_FAILURE,
where the latter two are defined in <cstdlib>, and the former means the
same as EXIT_SUCCESS. Other values are possible, but not portable.
<OT>
On unix systems the return value of 1 typically means failure of some
sort.
</OT>
To summarize: Get rid of the char*, and things should work.
/Niklas Norrthon