473,396 Members | 1,990 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,396 software developers and data experts.

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 2397
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******@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.


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

John Harrison wrote:
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


thanks John, I was hoping there was a better way.
Maybe that the string for object string s would remain
while it had a reference to it and remove it once that
reference is removed - but maybe thats java.

So my program above becomes:

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 = new char[s.size() + 1];
strcpy(ptr, s.c_str());

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

f1(mystruct);
cout << mystruct.cp << endl;
delete [] ms.cp;

return 0;
}

Nov 22 '05 #11
> int main () {
myStruct mystruct;

f1(mystruct);
cout << mystruct.cp << endl;
delete [] ms.cp;

return 0;
}


To find out whether this will work, I have to see what myStruct looks
like. Looks bad, though. Show us <myStruct> definition, then I'll
comment.

Regards,

Werner

Nov 22 '05 #12

werasm wrote:
int main () {
myStruct mystruct;

f1(mystruct);
cout << mystruct.cp << endl;
delete [] ms.cp;

return 0;
}


To find out whether this will work, I have to see what myStruct looks
like. Looks bad, though. Show us <myStruct> definition, then I'll
comment.

Regards,

Werner


Whoops sorry,

typedef struct {
char *cp;
} myStruct ;

Nov 22 '05 #13
dr******@gmail.com wrote:
Whoops sorry,

typedef struct {
char *cp;
} myStruct ;


I've looked at your example. It does not compile, firstly - where is
ptr declared in f1 (I'll assume you've meant ms.cp)? Also, the strcpy
omits copying the NULL terminator. This would mean streaming the
NON-terminated string to std::cout would envoke undefined behaviour, if
I'm not mistaken. All of this could have been achieved using:

int main()
{
std::cout << qwerty << std::endl;
return 0;
}

I don't see the point. Also, myStruct does not overload a copy
constructor/assignment operator/destructor. In general, the code is
bad. The only thing you are doing right, is that you call operator
delete[] when creating with operator new[] - good.

W

Nov 22 '05 #14
Thank you for looking at the code and apologies for the compile error.
Here is the compiled version:

typedef struct {
char *cp;
} myStruct ;

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

}

void f1(myStruct &ms)
{
string s;

f2(s);

ms.cp = new char[s.size() + 1];
strcpy(ms.cp, s.c_str());
ms.cp[s.size()]='\0';
}

int main () {
myStruct mystruct;

f1(mystruct);
cout << mystruct.cp << endl;
delete [] mystruct.cp;

return 0;
}

Please bear in mind I have created a simplified example to illustrate a
problem. The premise is having to deal with populating existing chars :
a one line cout statement isn't really the answer.

Nov 22 '05 #15

dr******@gmail.com wrote:
Thank you for looking at the code and apologies for the compile error.
Here is the compiled version:

typedef struct {
char *cp;
} myStruct ;
In c++ the typedef is redundant, therefore ...

struct myStruct
{
char* cp;
};
.... would have sufficed.

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

}
Even for you example, this (above) is unecessary.

void f1(myStruct &ms)
{
string s;

f2(s);

This could be:
std::string s( "qwerty" );

In general, it is good to qualify the std items explicitly.
ms.cp = new char[s.size() + 1]; Yes, this is how you allocate memory for the array. The size allocated
is correct as you require provision for a NULL terminator. s.size does
return the size of string excluding NULL terminator.
strcpy(ms.cp, s.c_str());
I would have used strncpy (or char_traits::copy) over here (actually I
would use strings :-) ).

strncpy( ms.cp, s.c_str(), s.size() )[s.size()] = '\0';

Note strncpy actually returns the destination string, therefore you
could use above syntax to terminate.
int main () { I would not have made char* part of struct.
myStruct mystruct;
char* myChar;

f1(myChar);

f1 then has signature <char*&>. IMO this still does not convey the
intent of the function, and it does not indicate to the receiver of
char* that he is required to delete it. It is less work and has the
same effect as your example though.

Therefore:

void f1( char*& out )
{
std::string qstr( "qwerty" );
const unsigned outSz( qstr.size()+1 );

out = new char[ outSz];
strncpy( out, qstr.c_str(), outSz-1 )[outSz];
}

int main()
{
char* myChar( 0 );
f1( myChar );
if( myChar )
{
std::cout << myChar << std::endl;
delete [] myChar;
}
return 0;
}

Also note that deleting a NULL ptr is valid, but sending NULL ptr to
std::cout may not be.

Kind regards,

W

Nov 22 '05 #16

werasm wrote:
dr******@gmail.com wrote:
Thank you for looking at the code and apologies for the compile error.
Here is the compiled version:

typedef struct {
char *cp;
} myStruct ;
In c++ the typedef is redundant, therefore ...

struct myStruct
{
char* cp;
};
... would have sufficed.

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

}


Even for you example, this (above) is unecessary.

void f1(myStruct &ms)
{
string s;

f2(s);


This could be:
std::string s( "qwerty" );

In general, it is good to qualify the std items explicitly.
ms.cp = new char[s.size() + 1];

Yes, this is how you allocate memory for the array. The size allocated
is correct as you require provision for a NULL terminator. s.size does
return the size of string excluding NULL terminator.
strcpy(ms.cp, s.c_str());


I would have used strncpy (or char_traits::copy) over here (actually I
would use strings :-) ).

strncpy( ms.cp, s.c_str(), s.size() )[s.size()] = '\0';

Note strncpy actually returns the destination string, therefore you
could use above syntax to terminate.


Actually, this is not necessary in this case, as the source is
guaranteed to be terminated, and strncpy reads until it finds a
terminator, then pads the rest therefore the above statement can
become:

strncpy( ms.cp, s.c_str(), s.size()+1 );

This will ensure ms.cp is terminated :-).
int main () { I would not have made char* part of struct.
myStruct mystruct;


char* myChar;

f1(myChar);

f1 then has signature <char*&>. IMO this still does not convey the
intent of the function, and it does not indicate to the receiver of
char* that he is required to delete it. It is less work and has the
same effect as your example though.

Therefore:

void f1( char*& out )
{
std::string qstr( "qwerty" );
const unsigned outSz( qstr.size()+1 );

out = new char[ outSz];
strncpy( out, qstr.c_str(), outSz-1 )[outSz];


Note that above statement should actually be...

strncpy( out, qstr.c_str(), outSz );

.... for reasons previously mentioned.
}

int main()
{
char* myChar( 0 );
f1( myChar );
if( myChar )
{
std::cout << myChar << std::endl;
delete [] myChar;
}
return 0;
}

Also note that deleting a NULL ptr is valid, but sending NULL ptr to
std::cout may not be.

Kind regards,

W


Nov 23 '05 #17

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

Similar topics

1
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...
3
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
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...
7
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...
12
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. ...
33
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...
3
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...
18
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
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). ...
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: 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?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.