473,769 Members | 1,994 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

char* dynamic strings - the right way

What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be
quite nice to avoid a memory leakage /core dump.

1 Header with char* x

2 Class includes header

3 In Class member function I want to :
a)conditionally create a string ie populate x
b)pass (populated) x on as a function parameter.

What is the right way of doing this for :
i) assigning string variable
ii) assigning a literal.

i) Since it's a conditional create I guess it is not a good idea to use
malloc or new.

ii) Is it ok to just have x = "some string";

Nov 8 '05 #1
16 2425
dr******@gmail. com wrote:
What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be
quite nice to avoid a memory leakage /core dump.
The right way, the easy way is to use std::string.

1 Header with char* x

2 Class includes header

3 In Class member function I want to :
a)conditionally create a string ie populate x
b)pass (populated) x on as a function parameter.

What is the right way of doing this for :
i) assigning string variable
ii) assigning a literal.

i) Since it's a conditional create I guess it is not a good idea to use
malloc or new.

ii) Is it ok to just have x = "some string";


I think you need to post the actual code you have written, it quite hard
to work out exactly what you mean, and if you really want to do it this
way then the details matter. But as I said the easy way is to drop char*
and use std::string instead.

std::string x;

x = "some string";
some_function(x );

What could be easier? No memory leaks, no core dumps.

john
Nov 8 '05 #2

John Harrison wrote:
dr******@gmail. com wrote:
What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be
quite nice to avoid a memory leakage /core dump.


The right way, the easy way is to use std::string.

1 Header with char* x

2 Class includes header

3 In Class member function I want to :
a)conditionally create a string ie populate x
b)pass (populated) x on as a function parameter.

What is the right way of doing this for :
i) assigning string variable
ii) assigning a literal.

i) Since it's a conditional create I guess it is not a good idea to use
malloc or new.

ii) Is it ok to just have x = "some string";


I think you need to post the actual code you have written, it quite hard
to work out exactly what you mean, and if you really want to do it this
way then the details matter. But as I said the easy way is to drop char*
and use std::string instead.

std::string x;

x = "some string";
some_function(x );

What could be easier? No memory leaks, no core dumps.

john


Dealing with existing code i.e.starting point is that I have a char*
and wish to either populate this in different ways : may call a func
that returns a char* or may wish to assign a string literal. So.

x = f(); being char* f() {...
x = "some string";

First though was to malloc/new to size of string/char array but it is
conditional as to whethr x gets populated.

Nov 8 '05 #3

dr******@gmail. com skrev:
John Harrison wrote:
dr******@gmail. com wrote:
What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be
quite nice to avoid a memory leakage /core dump.


The right way, the easy way is to use std::string.
[snip] std::string x;

x = "some string";
some_function(x );

What could be easier? No memory leaks, no core dumps.

john


Dealing with existing code i.e.starting point is that I have a char*
and wish to either populate this in different ways : may call a func
that returns a char* or may wish to assign a string literal. So.

x = f(); being char* f() {...
x = "some string";

First though was to malloc/new to size of string/char array but it is
conditional as to whethr x gets populated.

The easy way still is to use std::string. You really can't rely on
functions returning char* unless you really know what is going on
inside. You do not know how much memory (if any) has been allocated for
the array, you don't know if you have to free the pointer and you do
not know how to free it. Just start using std::string and encapsulate
your existing code (or rewrite it, if that is easier).

/Peter

Nov 8 '05 #4
dr******@gmail. com wrote:
John Harrison wrote:
dr******@gmai l.com wrote:
What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be
quite nice to avoid a memory leakage /core dump.


The right way, the easy way is to use std::string.

1 Header with char* x

2 Class includes header

3 In Class member function I want to :
a)conditiona lly create a string ie populate x
b)pass (populated) x on as a function parameter.

What is the right way of doing this for :
i) assigning string variable
ii) assigning a literal.

i) Since it's a conditional create I guess it is not a good idea to use
malloc or new.

ii) Is it ok to just have x = "some string";


I think you need to post the actual code you have written, it quite hard
to work out exactly what you mean, and if you really want to do it this
way then the details matter. But as I said the easy way is to drop char*
and use std::string instead.

std::string x;

x = "some string";
some_function (x);

What could be easier? No memory leaks, no core dumps.

john

Dealing with existing code i.e.starting point is that I have a char*
and wish to either populate this in different ways : may call a func
that returns a char* or may wish to assign a string literal. So.

x = f(); being char* f() {...
x = "some string";

First though was to malloc/new to size of string/char array but it is
conditional as to whethr x gets populated.


Whose responsibility is it to free the memory returned from f()?

Still dont see why you can't ise std::string

std::string x;

if (something)
x = f();
else
x = "some string";

john
Nov 9 '05 #5
dr******@gmail. com schrieb:
What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be
First of all, remember: char* is a _pointer_ to a char.
Not a string, not an array or anything else goofy. Just a pointer.
quite nice to avoid a memory leakage /core dump.
If you want to use char*, memory management is up to you. However, if
you use functions that return char*, you may rely on the fact, that the
memory is properly allocated there.

1 Header with char* x

2 Class includes header

3 In Class member function I want to :
a)conditionally create a string ie populate x
b)pass (populated) x on as a function parameter.

What is the right way of doing this for :
i) assigning string variable
ii) assigning a literal.

i) Since it's a conditional create I guess it is not a good idea to use
malloc or new.

ii) Is it ok to just have x = "some string";


What is the problem here? Hard to figure out what you mean, can you post
any code?
Eckhard
Nov 9 '05 #6

Eckhard Lehmann wrote:
dr******@gmail. com schrieb:
What is the right way of creating a string/char array and assigning to
a char* which is then used in a function call. Thought it would be


First of all, remember: char* is a _pointer_ to a char.
Not a string, not an array or anything else goofy. Just a pointer.
quite nice to avoid a memory leakage /core dump.


If you want to use char*, memory management is up to you. However, if
you use functions that return char*, you may rely on the fact, that the
memory is properly allocated there.

1 Header with char* x

2 Class includes header

3 In Class member function I want to :
a)conditionally create a string ie populate x
b)pass (populated) x on as a function parameter.

What is the right way of doing this for :
i) assigning string variable
ii) assigning a literal.

i) Since it's a conditional create I guess it is not a good idea to use
malloc or new.

ii) Is it ok to just have x = "some string";


What is the problem here? Hard to figure out what you mean, can you post
any code?
Eckhard


Ok here is some code but in other places I would deal with char* /
char[] and not a string.

void f2(string &s)
{
s="qwerty";
}

void f1(myStruct &ms)
{
string s;

f2(s);
// Error 203: # Cannot assign 'char *' with 'const char *'.
//ms.cp = s.c_str();

ms.cp = (char*)s.c_str( );
}
int main () {
myStruct mystruct;

f1(mystruct);
cout << mystruct.cp << endl;
return 0;
}

Note:
1) am stuck with using a char* - non-negotiable.
2) That I get Error 203 and need to cast seems to indicate this isn't
the correct way.
3) I did wonder if the s.c_str() would go out of scope leaving f1()
i.e. is this dangerous?
4) I would have thought it would be best to allocate memory to the
char* in main() but at that point the string size is unknown.

Sorry for the delay in responding.

Nov 22 '05 #7
dr******@gmail. com wrote:
2) That I get Error 203 and need to cast seems to indicate this isn't
the correct way.
Do you know what const means?
3) I did wonder if the s.c_str() would go out of scope leaving f1()
i.e. is this dangerous?
The return of c_str() ceases to be valid when a non-const method
(including the destructor) is run on the object.
4) I would have thought it would be best to allocate memory to the
char* in main() but at that point the string size is unknown.

So how would you do it?
Nov 22 '05 #8
I do not know the correct way of doing this - that is why I am posting
here!

1. You have a char *
2. You need to go off and populate this with a string or char array but
you do not know the size of the string., so....
3. string seems to be 'the' way of doing this but
a) c_str() returns a const and needs casting using char*
b) although the c_str() casting works and it is possible to print
the string out later - is this a case of something that will work
but not always?

Nov 22 '05 #9
dr******@gmail. com wrote:
I do not know the correct way of doing this - that is why I am posting
here!

1. You have a char *
2. You need to go off and populate this with a string or char array but
you do not know the size of the string., so....
3. string seems to be 'the' way of doing this but
a) c_str() returns a const and needs casting using char*
b) although the c_str() casting works and it is possible to print
the string out later - is this a case of something that will work
but not always?


You need to allocate memory

string s = "qwerty";
char* ptr = new char[s.size() + 1];
strcpy(ptr, s.c_str());
....
// sometime later when you are done
delete[] ptr;

It's because of this mess (particularly the need to delete[]) that you
should use strings instead of char, if you possibly can.

john
Nov 22 '05 #10

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

Similar topics

1
18006
by: Matt Garman | last post by:
What is the "best" way to copy a vector of strings to an array of character strings? By "best", I mean most elegantly/tersely written, but without any sacrifice in performance. I'm writing an application using C++ and the STL for handling my data. Unfortunately, I must interact with a (vanilla) C API. I use vectors of strings (for simplicity and less memory hassle), but the function calls for this API require arrays of character...
3
2211
by: sieg1974 | last post by:
Hi, I have made this simple program to understand char ** pointers, but I still having many questions. int main() { char ** testPointerPointerChar = 0; char * A = "string01";
2
5351
by: collinm | last post by:
hi i expect to find 7 file on a folder... maybe less, maybe more... i can surely put this number to 1... but i think doing some realloc will be expensive... after 7 files, i need to use realoc... somebody could help me to use realloc?
7
5640
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store strings of any lengths into an array of pointers to char type variable. my problem is: given the declaration
12
9583
by: leonard.guillaume | last post by:
Hi guys, I use dynamic char arrays and I'm trying to get rid of the garbage in it. Let me show you the code and then I'll explain more in details. ---------------------------------------------------------------------------------------------------- CFile oFile("User.tcx", CFile::modeRead); CRijndael oDecrypt; long size; char* buffer,* buf;
33
3678
by: Jordan Tiona | last post by:
How can I make one of these? I'm trying to get my program to store a string into a variable, but it only stores one line. -- "No eye has seen, no ear has heard, no mind can conceive what God has prepared for those who love him" 1 Cor 2:9
3
11779
by: DG is a god.... | last post by:
Dear All , This is my first post - please go easy...! I have a DLL written in C++ that has the following function exported from it -: char** ListHandles(int *processID); The processID parameter is used to find all associated open file
18
4063
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
12
3013
blackstormdragon
by: blackstormdragon | last post by:
Im having trouble with my classList variable. It's a dynamic array of strings used to store the names of the classes(my program ask for students name, number of classes, then a list of the classes). typedef char* CharPtr; class Student { public: Student& operator =(const Student& rightside); ~Student();
0
10205
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...
0
10035
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...
1
9984
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,...
1
7401
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
6662
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
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3949
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
2
3556
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2811
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.