473,883 Members | 3,128 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C Style Strings

Hi,

I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";

How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")

I looked at strcat but that crashes with an unhandled exception.

Thanks
Jun 1 '06
89 5191

SuperKoko wrote:
Even if it is popular in C. Many C libraries use another way:
GString is a good example of a clean C interface:
http://developer.gnome.org/doc/API/g...#G-STRING-FREE

Instead of having to call "free", the user must call a library-provided
resource deallocating function.
That is necessary to prevent heap corruption if the library and the
client code use different heap managers.

If the client is written in C++ you can use boost::scoped_p tr (or
shared_ptr) with a custom deleter that calls the deallocating function
when appropriate. So you can add your own RAII.

I am not totally against libraries allocating resource that require to
be freed, but if they do so it should be obvious. For example, a
library will often provide a class factory. If I ever have my libraries
create anything in this way, the function name always begins with (or
is called) create.
Using internally, functions which use with the any range of
user-provided memory (or iterators) is a good way to reuse efficiently
code.
However, in C, as in C++, it is good to encapsulate things and to
provide comfortable interfaces.


However when a library is written in C it is often written for
relatively low-level programming. Often a function will require you to
provide a buffer and its length. It will never overwrite the buffer but
will often flag you if the buffer you provided was inadequate. And
sometimes you can request ahead (at little cost) how big your buffer
needs to be.

C also has that wonderful technique of sticking a variable-length
buffer at the end of a structure thus:

struct some_type
{
header_info header;
char data[1];
};

but you malloc sizeof( header_info ) + actual_data_siz e (or safer
sizeof( some_type ) + data_size - 1 );

and then later on you call a "free" on the whole thing. It means that
you only have one "malloc" for everything. Beware that such a struct
cannot be safely copied though! (well if you do it will be sliced).

Jun 1 '06 #21
scroopy posted:
Hi,

I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";

How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")

I looked at strcat but that crashes with an unhandled exception.

Thanks

Maybe something like this.

Unchecked code:
void DestroyString( const char* const p )
{
delete [] p;
}

#include <cstddef>
#include <cstring>
#include <cstdlib>

char * const Concantenate( const char *a, const char *b )
{
std::size_t const len_a = std::strlen(a);
std::size_t const len_b = std::strlen(b);

char *p = new char[ len_a + len_b + 1 ];

std::memcpy( p, a, len_a );

std::memcpy( p + len_a, b, len_b + 1 );

return p;
}

#include <iostream>

int main()
{
char * const p = Concantenate("H ello ", "World!");

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

DestroyString(p );

std::system("PA USE");
}
-Tomás
Jun 1 '06 #22
kwikius wrote:
scroopy wrote:
Hi,

I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";

How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")

#include <malloc.h>

This is neither a C header nor a C++ header, so off-topic in both groups
to which you posted.
#include <cstring>

This is not a C header, so off-topic in one of the groups to which you
posted.

If you _must_ post to both <news:comp.lang .c++> and <news:comp.lang .c>,
try to make your post topical in each. As it stands, your post is
topical in neither.

There is hardly ever any excuse for posting to both newsgroups; these
are concerned with two different languages, and advice given in posts to
both is almost certainly going to be wrong, or at least non-idiomatic,
in at least one of them.
Jun 1 '06 #23
Martin Ambuhl wrote:
kwikius wrote:
#include <malloc.h>

This is neither a C header nor a C++ header, so off-topic in both groups
to which you posted.


Ok.
#include <cstring>

This is not a C header, so off-topic in one of the groups to which you
posted.


Ok.
If you _must_ post to both <news:comp.lang .c++> and <news:comp.lang .c>,
try to make your post topical in each. As it stands, your post is
topical in neither.
The code in the post attempts to highlight the different problems of
dealing with resource management in both languages. Having to deal
manually with resources and having to check results of functions for
validity are both sources of additional code complexity in C it seems.
Maybe there are plans to address this situation in the next version of
the C standard?
There is hardly ever any excuse for posting to both newsgroups; these
are concerned with two different languages, and advice given in posts to
both is almost certainly going to be wrong, or at least non-idiomatic,
in at least one of them.


If I have given incorect advice, I apologise. FWIW I certainly dont
advocate use of malloc or C-style strings or manual memory management.
IOW I advocate use of C++ over C. C holds no advantage whatever. The
concat function shows very neatly why it is best to avoid C-style
strings in C++. In C it seems that it is possible to do better though
there seems to be no standard higher level string library. Maybe there
are plans to address this situation in the next version of the C
standard?

Whatever... Happy coding!

regards
Andy Little

Jun 1 '06 #24
kwikius wrote:
char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";
int main()
{
// C-style
char* str = concat(pString1 ,pString2);
if(str != NULL){
std::cout << str <<'\n';
free(str);
}

// C++ style
std::string str1=std::strin g(pString1) + pString2;
std::cout << str1 <<'\n';
}

I'm not sure if that is the optimal C method. Its interesting to note
how much better the C++ version is though!


yeah, it's always better when programs randomly drop
"terminate called after throwing an instance of 'std::bad_alloc '
what(): St9bad_alloc
Aborted"
messages on the screen and then stop working.

Jun 2 '06 #25
kwikius wrote:
Martin Ambuhl wrote:
kwikius wrote:
.... snip ...
The code in the post attempts to highlight the different problems of
dealing with resource management in both languages. Having to deal
manually with resources and having to check results of functions for
validity are both sources of additional code complexity in C it seems.
Maybe there are plans to address this situation in the next version of
the C standard?
I guess you want garbage collection and exceptions support. Both impose
run-time overhead. Increasingly, C is used in embedded programming
where both might be unfeasible and unnecessary. I don't think there is
much chance that they will be standardised.

Third-party garbage collectors are available for C. But if you really
want these features built into the langauge, maybe you should consider
Java?
If I have given incorect advice, I apologise. FWIW I certainly dont
advocate use of malloc or C-style strings or manual memory management.
Good for you.
IOW I advocate use of C++ over C. C holds no advantage whatever.
It depends on what you're trying to do. Sweeping generalisations aren't
correct.
The concat function shows very neatly why it is best to avoid C-style
strings in C++.
Indeed. If you decide to program in C++, then you should program in
C++.
In C it seems that it is possible to do better though
there seems to be no standard higher level string library.
Yes, anyone who wants an abstract string library has to either roll his
own or use pre-existing ones. The former case, especially, allows one
to optimise for their specific requirements, though I don't think the
code will be significantly better than std::string.
Maybe there are plans to address this situation in the next version of the C
standard?


I doubt it. Even the next revision of the standard is a minimum of 3-4
years away, and the standard committee have always resisted turning C
into another C++/Java wannabe.

Jun 2 '06 #26
kwikius <an**@servocomm .freeserve.co.u k> wrote:
In C it seems that it is possible to do better though
there seems to be no standard higher level string library. Maybe there
are plans to address this situation in the next version of the C
standard?


One very big difference between C and some other languages (say, Java
and C# and VB, for example) is that there is no big organization that's
got billions of dollars invested in making C the next Big Thing. As a
result, the language is not as large or complex, and far more stable,
than some of these other languages. I doubt you'll see future versions
of C making really huge changes in the language or APIs to conform with
higher-level programming goals. After all, if you wanted this you
wouldn't use C, and the standards organization doesn't particularly care
if you use C or not.

Short answer: probably not.

--
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
Jun 2 '06 #27
santosh wrote:
kwikius wrote:
... snip ...
The code in the post attempts to highlight the different problems of
dealing with resource management in both languages. Having to deal
manually with resources and having to check results of functions for
validity are both sources of additional code complexity in C it seems.
Maybe there are plans to address this situation in the next version of
the C standard?
I guess you want garbage collection and exceptions support. Both impose
run-time overhead. Increasingly, C is used in embedded programming
where both might be unfeasible and unnecessary. I don't think there is
much chance that they will be standardised.


Yes. C++ claims to be as useable as C in embedded systems, but I have
heard that use of exceptions rather than error codes causes problems.
There is a marginal effect on performance but AFAIK the larger problems
are due to the latency involved in unwinding the stack as well as
apparently extra memory use for the exception handling code. I guess
that the different style of error handling also causes major problems
with integration. There is probably also an element of sticking with
the way things have always been done. AFAIK Most compilers can turn
off exceptions, though I think this is non-standard even in the
so-called free-standing c++ implementations .
Third-party garbage collectors are available for C. But if you really
want these features built into the langauge, maybe you should consider
Java?


I kind of like Java Swing.
If I have given incorect advice, I apologise. FWIW I certainly dont
advocate use of malloc or C-style strings or manual memory management.


Good for you.
IOW I advocate use of C++ over C. C holds no advantage whatever.


It depends on what you're trying to do. Sweeping generalisations aren't
correct.


Actually after posting I am pretty sure that the C code will be faster.
Creating a C++ string probably involves an allocation. The C++ string
concat operator(+) may also involve an allocation,wher eas the C code
only has one allocation. That is the downside of automated resource
management.
The concat function shows very neatly why it is best to avoid C-style
strings in C++.


Indeed. If you decide to program in C++, then you should program in
C++.


Well I like other languages too. I like the platform independent spirit
of Java and its GUI support, but I guess I would miss C++.

regrads
Andy Little

Jun 2 '06 #28
kwikius wrote:
Martin Ambuhl wrote:
kwikius wrote:
#include <malloc.h> This is neither a C header nor a C++ header, so off-topic in both groups
to which you posted.


Ok.
#include <cstring>

This is not a C header, so off-topic in one of the groups to which you
posted.


Ok.
If you _must_ post to both <news:comp.lang .c++> and <news:comp.lang .c>,
try to make your post topical in each. As it stands, your post is
topical in neither.
These guys are real great at keeping the snow out of their cave, even
if they don't realize that its part of an avalanche on top of them.
The code in the post attempts to highlight the different problems of
dealing with resource management in both languages. Having to deal
manually with resources and having to check results of functions for
validity are both sources of additional code complexity in C it seems.
Maybe there are plans to address this situation in the next version of
the C standard?
The C standard is not something where people try to actually address
actual real world problems. You can look at their own manifesto --
they claim to "endorse standard practice" and things along those lines.
So in a sense they *endorse* all the problems with the C language, so
long as it is standard practice. Hence the continuing presence of
"gets" in the library.

C++ obviously goes a long way to addressing resources and error
handling in a useful way (RAII and real exception handling) however it
is not a garbage collecting language and thus it will always take a
little more effort to program in it properly. And of course C leaves
the whole concept of construction and destruction up to the programmer.
There is hardly ever any excuse for posting to both newsgroups; these
are concerned with two different languages, and advice given in posts to
both is almost certainly going to be wrong, or at least non-idiomatic,
in at least one of them.


If I have given incorect advice, I apologise. FWIW I certainly dont
advocate use of malloc or C-style strings or manual memory management.
IOW I advocate use of C++ over C. C holds no advantage whatever.


Well hang on -- this is precisely where you can make an argument for C
over C++. In C since you are forced to do everything by hand, you have
the advantage of being able to do everything by hand. For example, you
use local stack based memory to back certain allocations if you know
that the lifetime of the resource is equal to the lifetime of the
function call. In C++ you can hope your compiler can figure it out; if
not it will use new/delete which eventually falls back to malloc/free
which is hundreds of times slower.
[...] The
concat function shows very neatly why it is best to avoid C-style
strings in C++. In C it seems that it is possible to do better though
there seems to be no standard higher level string library. Maybe there
are plans to address this situation in the next version of the C
standard?


Take a look at http://bstring.sf.net/ . I claim that even just the C
API is generally better than C++'s std::string, or Microsoft's CString
classes. But it includes a C++ API as well which should make everyone
happy.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Jun 2 '06 #29

we******@gmail. com wrote:
C++ obviously goes a long way to addressing resources and error
handling in a useful way (RAII and real exception handling) however it
is not a garbage collecting language and thus it will always take a
little more effort to program in it properly.
RAII is not possible in a garbage collected language. Garbage
collection can, in many real world cases, add more complexity than it
is meant to solve.
Well hang on -- this is precisely where you can make an argument for C
over C++. In C since you are forced to do everything by hand, you have
the advantage of being able to do everything by hand. For example, you
use local stack based memory to back certain allocations if you know
that the lifetime of the resource is equal to the lifetime of the
function call. In C++ you can hope your compiler can figure it out; if
not it will use new/delete which eventually falls back to malloc/free
which is hundreds of times slower.


That statement about C++ is simply incorrect; I can't even imagine
where it is coming from.

Jun 2 '06 #30

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

Similar topics

6
8326
by: Christopher Benson-Manica | last post by:
I have a C-style string (null-terminated) that consists of items in one of the following formats: 14 characters 5 characters space 8 characters 6 characters colon 8 characters 5 characters colon 8 characters Items are delimited by semicolons or commas. I have to produce a string delimited only by semicolons and containing items in the first two formats only. For example,
5
2431
by: Curtis Gilchrist | last post by:
I am required to read in records from a file and store them in descending order by an customer number, which is a c-style string of length 5. I am storing these records in a linked list. My problem is in comparing the customer number I just read in with those in the list. I'm not sure how to go about comparing c-style strings for greater than, less than.. here is how I am currently trying to do it: while( ( custinfo.number >...
3
2128
by: joealey2003 | last post by:
Hi all... I included a css file on my html and i need to check some properties. The html is: <style id="myid" src="mycsspage.css"> </style> Now i need something to access it like: alert(document.getElementById("myid").bottomline.color);
7
1953
by: seans | last post by:
Hi, I need to change the font, font size, and color of a button on a form. I need to save the current style settings and restore them later. Is there an easy way of doing that? Sorry if there is a simple solution to this; I am still learning Javascript. Thanks again.
5
10233
by: Chuck Bowling | last post by:
Maybe I'm doing something wrong or just don't understand the concept, but i'm having a problem with default properties. My impression of how a default property should act is this; MyClass c = new MyClass(); c = "my text"; In the line above, the string is assigned to a field in the class instance.
2
1419
by: Xiaoshen Li | last post by:
Dear All, I hear a lot that cstring cannot be changed. But my code: /************************************************************* * Testing cstring(a pointer) * **********************************************************/ #include <iostream> using namespace std;
4
2017
by: Kza | last post by:
Hi, just in the process of maintaining some software that used some funy old string library and char*s , and we are updating everything to use std::strings. (or should I say std::basic_string<>s) I find it wierd that that all the new c++ ansi style librarys like the streams and file handling classes still expect us to use old style char* type strings. For example, ofstreams open function expects the filename as a char* parameter rather...
2
2232
by: Kamjah Kogumah | last post by:
A Dev Opera article suggest using code 2 instead of code 1 in performance-critical functions. code 1: a += 'x' + 'y'; code 2: a += 'x'; a += 'y';
16
3682
by: yu_kuo | last post by:
Is there any comparison data on perfomance difference between std::string and c style string? Or maybe if there are source code which could be used to measuer on different compiler/platform, in a systematic way?
0
9797
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
10762
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10422
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9586
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
7977
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
7136
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
6005
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3241
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.