473,378 Members | 1,412 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

String ctor

Why does the below program crash?

#include <string>

using namespace std;

int main()
{
string name = 0;
return 0;
}
Jul 23 '05 #1
10 2787
* giles:
Why does the below program crash?

#include <string>

using namespace std;

int main()
{
string name = 0;
return 0;
}


How many times are you going to ask this question?

Oh well, it's because the standard defines the string constructor that way.

Happy now?

--
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?
Jul 23 '05 #2
If you want to initialize a string do:
-#include <string>
-
-using namespace std;
-
-int main()
-{
- string s = "";
- string t("");
-
- return 0;
-}

Jul 23 '05 #3

"Alf P. Steinbach" <al***@start.no> wrote in message
news:42*****************@news.individual.net...
Oh well, it's because the standard defines the string constructor that

way.

Any idea why the standard doesn't define std::string spoo(0) to create
an empty string? Seems like a good idea.

Jul 23 '05 #4
Val

"giles" <gi***************@yahoo.co.in> wrote in message news:2a**************************@posting.google.c om...
| Why does the below program crash?
|
| #include <string>
|
| using namespace std;
|
| int main()
| {
| string name = 0;
| return 0;
| }

Why does the program below behave weird?

int main()
{
unsigned number = "Hello world".
return 0;
}
Jul 23 '05 #5

"Duane Hebert" <sp**@flarn.com> wrote in message
news:UQ*******************@news20.bellglobal.com.. .

"Alf P. Steinbach" <al***@start.no> wrote in message
news:42*****************@news.individual.net...
Oh well, it's because the standard defines the string constructor that way.

Any idea why the standard doesn't define std::string spoo(0) to create
an empty string?


Because it doesn't need to. There are already two other
constructors which can create an empty string:

std::string s;

std::string s("");

Passing zero as the argument to the second one (as the
OP was doing), is passing a null pointer -- undefined behavior.
Seems like a good idea.


Not to me.

-Mike
Jul 23 '05 #6
"Duane Hebert" <sp**@flarn.com> wrote in message news:<UQ*******************@news20.bellglobal.com> ...
"Alf P. Steinbach" <al***@start.no> wrote in message
news:42*****************@news.individual.net...
Oh well, it's because the standard defines the string constructor that

way.

Any idea why the standard doesn't define std::string spoo(0) to create
an empty string? Seems like a good idea.


For consistency. Constructing a std::string object from a single
integral value invokes the std::basic_string(const Char* p, const
Allocator& a = Allocator()) constructor. This kinda works just like
the C library functions strcpy(), strcat(), strlen(), and so on.

You will find that those C functions do not treat a null pointer as a
null string (some implementation may, but dereferencing a null pointer
yields undefined behaviour). All my favorite C library
implementations signal an error.

Another reason is the pay-for-what-you-use principal. Why should
every string construction have to pay the price of a null-check just
in case?

--
Stephen M. Webb
Jul 23 '05 #7
Val wrote:
"giles" wrote:
| Why does the below program crash?
|
| int main()
| {
| string name = 0;
| return 0;
| }

Why does the program below behave weird?

int main()
{
unsigned number = "Hello world".
return 0;
}


Slight difference: your program (with typoes fixed) requires
a compiler diagnostic, but the OP program doesn't.

Jul 23 '05 #8
giles wrote:
Why does the below program crash? cat main.cc #include <string>

int main(int argc, char* argv[]) {
std::string name = 0;
return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

terminate called \
after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct NULL not valid
Abort (core dumped)

Because that's what is supposed to happen
when you fail to catch an exception.
Next time, show us your compiler and options
and include any compile-time diagnostics
and run-time error messages that you got.
Jul 23 '05 #9
"Stephen M. Webb" wrote:

"Duane Hebert" <sp**@flarn.com> wrote in message news:<UQ*******************@news20.bellglobal.com> ...
"Alf P. Steinbach" <al***@start.no> wrote in message
news:42*****************@news.individual.net...
Oh well, it's because the standard defines the string constructor that way.

Any idea why the standard doesn't define std::string spoo(0) to create
an empty string? Seems like a good idea.


For consistency. Constructing a std::string object from a single
integral value invokes the std::basic_string(const Char* p, const
Allocator& a = Allocator()) constructor. This kinda works just like
the C library functions strcpy(), strcat(), strlen(), and so on.

You will find that those C functions do not treat a null pointer as a
null string (some implementation may, but dereferencing a null pointer
yields undefined behaviour). All my favorite C library
implementations signal an error.


True. But C++ tries to make programmers life easier by not having
to constantly deal with exceptions.
In practice this means that most of the time when someone creates a std::string
from a const char* he has to check that pointer.

Another reason is the pay-for-what-you-use principal. Why should
every string construction have to pay the price of a null-check just
in case?


The same could be said for delete.
Why does delete need to check for NULL, just in case.

Note: I don't consider "This has been so in C" as a very good argumentation.
After all, millions of C programmers lived happily with dynamically allocating
arrays and yet someone felt the need to introduce std::vector to solve a problem.
So the fact that strxxx() doesn't deal with NULL pointers in a logical way
can't be an argument.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #10
In message <d3**********@nntp1.jpl.nasa.gov>, E. Robert Tisdale
<E.**************@jpl.nasa.gov> writes
giles wrote:
Why does the below program crash?
> cat main.cc

#include <string>

int main(int argc, char* argv[]) {
std::string name = 0;
return 0;
}
> g++ -Wall -ansi -pedantic -o main main.cc
> ./main

terminate called \
after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct NULL not valid
Abort (core dumped)

Because that's what is supposed to happen
when you fail to catch an exception.


Oh. Which exception does the standard mandate for dereferencing a null
pointer?
Next time, show us your compiler and options
and include any compile-time diagnostics
and run-time error messages that you got.


--
Richard Herring
Jul 23 '05 #11

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

Similar topics

15
by: G. Peter | last post by:
Hi there, I've a 'funny' error message of my compiler (g++ 2.95.4) that tells me: robot.cpp: In method `Robot::Robot()': robot.cpp:19: warning: deprecated conversion from string constant to...
3
by: syhart | last post by:
Please, anyone who has experience setting up a sql connection string in the web.config file, can you decipher this error.: Keyword not supported: 'datasource'. Description: An unhandled...
8
by: Baloff | last post by:
Hello I am not sure why my compiler will not initialize string e1("sam"); and will initialize string e1 = "sam"; here is my code and the error. thanks alot
1
by: Sandra | last post by:
I am trying to convert a string into a uniqueidentifier by using the following code string contrID = Request.Params["oId" SqlGuid sqlID = SqlGuid.Parse(contrID I am then putting sqlID into my...
0
by: Gaurav | last post by:
Hi, I have a connection string "Data Source=db1.mynet;DATABASE=test;User ID=testuser;Password=test;" , when i use the connection string to get a dataset of all the tables of a database it...
0
by: andy | last post by:
Hi all, Any help much appreciated - Andy I am trying to connect to a SQL Server DB using c#, ADO.Net mySqlConnection = new...
12
by: eastern_strider | last post by:
Hi, Is it safe to have a pointer to a string.c_str() created locally inside a function? For example, would the following code give me headace if a try to use "c" after calling foo() ? const...
8
by: Grizlyk | last post by:
Good morning. Look here: http://groups.google.com/group/fido7.ru.cpp.chainik/browse_frm/thread/7341aba5238c0f79 and here:...
2
by: subramanian100in | last post by:
If we do not provide any ctor for a class, the compiler provides the default ctor and copy ctor if needed. Consider a class Test. Suppose we provide some ctor in class Test but do not provide...
6
by: arnuld | last post by:
This works fine, I welcome any views/advices/coding-practices :) /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a program to store each line from a file into a *...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.