473,799 Members | 3,210 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer string assignment problem

Hi Group,
When i compile the following program it compiles successfully, but
crashes while executing. I am trying to assign a NULL char pointer to a
string. The error message is

/home1/murugan/prog/ccprog >./a.out
Abort(coredump)
/home1/murugan/prog/ccprog >
The program is :

#include <iostream>
#include <string>

using namespace std;

int main()
{
string request;
char* str = 0;

request = str;
cout<<endl<<req uest<<endl;
return 1;
}

Thanks in advance.

Cheers
Shan

Dec 2 '05 #1
5 6244
* sh*******@yahoo .com:

When i compile the following program it compiles successfully, but
crashes while executing. I am trying to assign a NULL char pointer to a
string.


You can't, or at least, shouldn't.

std::string has no representation of null-strings.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 2 '05 #2
On 1 Dec 2005 21:38:23 -0800, sh*******@yahoo .com wrote:
Hi Group,
When i compile the following program it compiles successfully, but
crashes while executing. I am trying to assign a NULL char pointer to a
string. The error message is

/home1/murugan/prog/ccprog >./a.out
Abort(coredump )
/home1/murugan/prog/ccprog >
The program is :

#include <iostream>
#include <string>

using namespace std;

int main()
{
string request;
char* str = 0;

request = str;
cout<<endl<<req uest<<endl;
return 1;
}

Thanks in advance.

Cheers
Shan

You may assign a char pointer to a string provided a) it is not a null
pointer and b) it points to a C string (that is, terminated with a
'\0'.

If your aim is to assgin an empty string, there are various ways, two
of them are: request.clear() and request="",

Regards,
-- Zara
Dec 2 '05 #3
Zara wrote:
On 1 Dec 2005 21:38:23 -0800, sh*******@yahoo .com wrote:

You may assign a char pointer to a string provided a) it is not a null
pointer and b) it points to a C string (that is, terminated with a
'\0'.

If your aim is to assgin an empty string, there are various ways, two
of them are: request.clear() and request="",

Regards,
-- Zara


Thank you guys. It was an old code and we are trying to find out an
work around. The code i sent to the group simulates the problem which
we are facing in the real code.

Cheers
Shan.

Dec 2 '05 #4
sh*******@yahoo .com writes:
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.
char* str = 0;
This line creates a pointer to char, initializing it to NULL, that
is it doesn't point anywhere.
request = str;
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<<req uest<<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.
return 1;


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
Dec 2 '05 #5
Niklas Norrthon <do********@inv alid.net> wrote:
sh*******@yahoo .com writes:
cout<<endl<<req uest<<endl;


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.


I think the most significant difference is that

std::cout << std::endl;

is basically equivalent to

std::cout << '\n' << std::flush;

which _might_ affect performance. If you know you _need_ to flush the
stream, std::endl should be fine. Personally, I usually use '\n' also,
except in my logging class.

--
Marcus Kwok
Dec 2 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2880
by: stub | last post by:
Some questions about "this" pointer: 1. To make an assignment function, Stribg &String::operator=(const String &other) { ... return *this; }
8
2365
by: chessc4c6 | last post by:
The program below creates a char pointer call charPtr...... i then declare an char array string "Good Luck" When i assign charPtr = string, I expect an error. However, It actually runs and outputs: G Good Luck
33
5085
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
3
2972
by: john | last post by:
Hey, I know we use the pointer this to obtain a class object or class member data. I don't follow the reason for example this code. I'am quite confused assingment operator const B &operator=(const B& x){ if (&x != this)
2
35631
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently. Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting...
8
2053
by: somenath | last post by:
Hi All, I have a doubt regarding the pointer assignment . Please have a look at the following program . #include<stdio.h> #include<stdlib.h> #define NAMESIZE 10 #define SAFE_FREE(t) if(t)\ {\
23
4785
by: =?iso-8859-1?q?Santiago_Urue=F1a?= | last post by:
Hi, I tried to return a pointer to a constant string, but the compiler gives the following warning if a cast is not used: warning: assignment from incompatible pointer type This is the code:
20
2247
by: MikeC | last post by:
Folks, I've been playing with C programs for 25 years (not professionally - self-taught), and although I've used function pointers before, I've never got my head around them enough to be able to think my way through what I want to do now. I don't know why - I'm fine with most other aspects of the language, but my brain goes numb when I'm reading about function pointers! I would like to have an array of structures, something like
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10490
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10243
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9078
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7570
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.