• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
jeff8j

c++ string pointer to char*

20 posts in this topic

I am trying to avoid making an unnecessary copy of my data as I believe string->c_str() would do
so im trying to point directly to the string data like &string[0]
but my problem is I have a string pointer like this

[code]
void somefunction( std::string* data ){
someotherfunction( data->c_str() ); //needs char*
}
[/code]

how can I do the equivalent of &data[0] with the pointer?
2

Share this post


Link to post
Share on other sites
edit: Sorry I completely misread your post.

Time for some more coffee =) Edited by yewbie
1

Share this post


Link to post
Share on other sites
Jeff, check out this link, it has some interesting reading on the subject:

http://bytes.com/topic/c/answers/164645-does-c_str-property-string-class-allocate-memory
1

Share this post


Link to post
Share on other sites
Note if you want to use the subscript operator on a pointer to a string you can use (*data)[0].
2

Share this post


Link to post
Share on other sites
Thanks Cornstalks thats good news now I would assume its c++11 not sure about the cross compiler though but ill give it the benefit of the doubt for now.

@SiCrane Thats what I was thinking but I get the warning warning: cast to pointer from integer of different size and a seg fault when running

Thanks everyone its much clearer in my head now everything is working with the c_str()
2

Share this post


Link to post
Share on other sites
One more thing to keep in mind with c_str()... DO NOT SAVE A COPY.

Period, ever. Nope, very zilch never. Got it?

A c_str() pointer dies with the containing object, leaving your reference dangling like a hand grenade waiting to explode. Also, any non-const method call on the originating std::string object will invalidate your pointer.

Therefore, always request a new c_str().
2

Share this post


Link to post
Share on other sites
In your original post only pointers are being copied. However c_str() can create a new internal cstring that IS guaranteed to be null terminated. Using that function is likely causing the extra memory usage. And as it was said before, any modification of the std::string or it's deletion will result in an the returned pointer from c_str() to be an invalid dangling pointer (. There is no way around this with std::string.c_str(). If you want other functionality such as a class that holds one and only one c string inside it then write your own, it isn't hard.

If you want to keep the value returned from c_str() you will need to copy it yourself.

[source lang="cpp"]

std::string mystr = "Hello world!";

const char *cstr = mystr.c_str();

char *copiedCStr = new char[strlen(cstr) + 1];

strcpy(copiedCStr, cstr);
[/source] Edited by EddieV223
0

Share this post


Link to post
Share on other sites
[quote name='EddieV223' timestamp='1348202840' post='4982237']
[b]However c_str() can create a new internal cstring[/b] that IS guaranteed to be null terminated.
[/quote]
In C++03, yes. In C++11, no.

[quote name='EddieV223' timestamp='1348202840' post='4982237']
Using that function is likely causing the extra memory usage.
[/quote]
I actually find that very unlikely. The popular implementations that I know of certainly don't. It's technically possible, yes (if he's using C++03), but it's unlikely he's working with an implementation that does so, just because most implementations (both C++03 and C++11) don't create a whole copy of the string when c_str() is called. As the OP stated in a later post: "It was me that was doing the extra memory allocation I falsely blammed c_str()"

[quote name='EddieV223' timestamp='1348202840' post='4982237']
If you want to keep the value returned from c_str() you will need to copy it yourself.
[code]
std::string mystr = "Hello world!";

const char *cstr = mystr.c_str();

char *copiedCStr = new char[mystr.size() + 1]; // no need to call an O(n) function when an O(1) function is available

strcpy(copiedCStr, cstr);
[/code]
[/quote]
Made a small improvement. Edited by Cornstalks
1

Share this post


Link to post
Share on other sites
@Serapth Im just using it for reading anyways its a encryption function so 1pointer for input and 1 for output is how im doing it

@Cornstalks your right it was my fault its not allocating any noticeable difference but it turns out im not using c++11 as when I try the c++11 threads it gives me something saying thats coming in the future so im still concerned that on various compiers/cross compiling and older version of c++ is used

To try to be on the safe side (im sure im not guaranteed anythingbut lets me sleep better) after getting some sleep I was able to setup the pointer with
(const unsigned char*)&(*data)[0]
That works just fine and fingers crossed will never allocate any memory across the board
0

Share this post


Link to post
Share on other sites
I would not do that. Ever. Any sane implementation on which [code](const unsigned char*)&(*data)[0][/code] works will not allocate any extra memory because c_str() can already just return the internal buffer. Any implementation which does allocate memory will not have a contiguous memory block for its string and [code](const unsigned char*)&(*data)[0][/code] will just cause horrible problems.
0

Share this post


Link to post
Share on other sites
There is no guarantee that the internal representation of a std::string is null terminated, so you could not pass that pointer to a function expecting a c string - presumably the very thing you are trying to accomplish.
0

Share this post


Link to post
Share on other sites
As I and others have said, &(*data)[0] is horribly unsafe. Plus, it's an obvious enough operation that if it is a safe operation, you can expect your Standard Library implementors to have implemented c_str() as something like that. Your Standard Library implementors are actually brilliant people, and they won't unnecessarily copy a string if it can be avoided.

If you're so concerned about the performance of c_str(), why not just look at how it's defined and make sure it doesn't create a copy? My gcc implementation defines [font=courier new,courier,monospace]std::basic_string::c_str()[/font] as just [font=courier new,courier,monospace]_M_data()[/font], and [font=courier new,courier,monospace]_M_data()[/font] is defined as [font=courier new,courier,monospace]return _M_dataplus._M_p;[font=arial,helvetica,sans-serif], so it absolutely does not create a copy.[/font][/font]

[font=courier new,courier,monospace][font=arial,helvetica,sans-serif]Just check your implementation of c_str() if you're paranoid, and only use implementations that don't create a copy. But again, as I've said, it's unlikely you'll find an implementation that creates a copy of the data if you're not using an exotic system/compiler (and if you were, you'd probably already be aware of things like this).[/font][/font]
0

Share this post


Link to post
Share on other sites
If you are concerned about copies of data going to memory and need to use a null terminated string anyway, why not use a char buffer? (Is that taboo now?)
0

Share this post


Link to post
Share on other sites
@cornstalks Im not too concerned anymore knowing its not at least in my current system but I would almost rather it break than start swapping out and become horribly slow. Im just worried on cross compiling for arm devices since im sure they put far less time into the implementations than x86 but ill cross that path if it ever arises.

@yewbie lol pretty much I dont have to worry about null terminations and keeping the size for binary data, not that its difficult just why do it when strings are cleaner and easier well there is this scenario when I would have more control but I dont believe I need it now that we covered everything.
0

Share this post


Link to post
Share on other sites
[quote name='jeff8j' timestamp='1348248277' post='4982438']
@cornstalks Im not too concerned anymore knowing its not at least in my current system but I would almost rather it break than start swapping out and become horribly slow.
[/quote]
The problem is if it doesn't break---at first. It could work for you and your test cases, and then for a set of customers horribly fail. Plus, even if it never breaks, it introduces a potential security flaw.

[quote name='jeff8j' timestamp='1348248277' post='4982438']
Im just worried on cross compiling for arm devices since im sure they put far less time into the implementations than x86 but ill cross that path if it ever arises.
[/quote]
I would still be very surprised if an ARM implementation had c_str() create and return a copy. It's more work for the programmer who writes the std::basic_string implementation to create a string class that uses multiple allocations instead of one contiguous allocation, and it's even more work to create a copy than to return a pointer to it. So if they're lazy, c_str() is, in my opinion, even more likely to not create a copy.
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1348150523' post='4982032']
Your code should work as long as [font=courier new,courier,monospace]someotherfunction[/font] takes a [font=courier new,courier,monospace]const char*[/font].

If the problem is that it takes a [font=courier new,courier,monospace]char*[/font] (but does promise not to write to the buffer), then you can use the const-correctness hack:[code]someotherfunction( const_cast<char*>(data->c_str()) );//C++ style
someotherfunction( (char*)(data->c_str()) );//or C-style casting[/code]
[/quote]

You beat me to the chase Hodge. Const keyword guarantees it won't change unless specified.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0