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

string copy

bml
char s1 = "this string";

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);

/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');

/* Why empty content of s2 print out here*/

Thanks a lot!
Nov 14 '05 #1
13 11424
bml wrote:
char s1 = "this string";

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);

/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');

/* Why empty content of s2 print out here*/


Hint: What is s2 now pointing to?

[BTW -- in the future, post *real* code (the most minimal possible
runnable snippet); otherwise we're just guessing.]

HTH,
--ag

--
Artie Gold -- Austin, Texas
Nov 14 '05 #2
bml wrote:
char s1 = "this string"; ^^ missing '*'
char *s2;
s2 = (char *)malloc(30); ^^^^^^^ silly cast
No error check memset(s2, 0, 30); ^^^^^^^^^^^^^^^^^
useless function call
/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');

/* Why empty content of s2 print out here*/ You were unlucky; your computer should have exploded.
Because s2 points beyond the end of the string. What did you think was
happening when you incremented it?
Thanks a lot!


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
char *s1 = "this string";
char *t1 = s1;
char *s2;
char *t2;
if (!(s2 = malloc(strlen(s1) + 1))) {
fprintf(stderr, "malloc failed for s1\n");
exit(EXIT_FAILURE);
}
t2 = s2;
while ((*t2++ = *t1++)) ;
printf("s1: \"%s\"\ns2: \"%s\"\n", s1, s2);
return 0;
}

--
Martin Ambuhl
Nov 14 '05 #3
"bml" <le*****@yahoo.com> writes:
char s1 = "this string";
I assume this is a typo and you meant to write

char *s1 = "this string";
char *s2;
s2 = (char *)malloc(30);
Don't cast malloc. It is not necessarry and may hide a serious error
if you forget to include <stdlib.h> (which provide the prototype for
malloc).
memset(s2, 0, 30);
Make sure malloc succeeded before accessing s2.

if (s2 != NULL)
/* use s2 here */

If you simply want to "empty" the string then *s2 = '\0' will do.
/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');
Why not simply use strcpy?
/* Why empty content of s2 print out here*/


Where does s2 point after the loop completes? You'll need to remember
the original pointer,

char *t = s2;
while (*s2++ = *s1++);
s2 = t;
printf ("%s\n", s2);
Nov 14 '05 #4
On 1 Feb 2004, Thomas Pfaff wrote:
Where does s2 point after the loop completes? You'll need to remember
the original pointer,

char *t = s2;
while (*s2++ = *s1++);
s2 = t;


char *t = s2;
while (*t++ = *s1++) ;

If this seems like a mindless nit I'm probably just overly biased against
the idiom of modifying a variable and then popping it back..

Nov 14 '05 #5
bml wrote:
char s1 = "this string";
const char * s1 = "this string";
Always treat string literals as constants. Thus
s1 is declared as a pointer to constant data.
Constant meaning it won't change.

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);
char * s2;
if (strlen(s1) < 30)
{
s2 = malloc(30);
}
else
{
s2 = malloc(strlen(s1) + 1);
}
if (s2 == NULL)
{
/* error processing */
}


/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');
strcpy(s2, s1); /* copy string s1 to s2 */


/* Why empty content of s2 print out here*/
puts("String s2:");
puts(s2);

Thanks a lot!


--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 14 '05 #6
In 'comp.lang.c', "bml" <le*****@yahoo.com> wrote:
char s1 = "this string";

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);

/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');

/* Why empty content of s2 print out here*/


Empty ? I'm not sure. I would have said 'undeterminated', due to the lack of
final 0.

add :
*s2 = 0;

but you are making a design mistake. You have changed the value of s2, hence
you have lost it's initial value:

- The string copy was somehow correct, but you don't know any more where does
the copied string begin.
- You are now unable to free the allocated block which has created a memory
leak. (A Bad Thing (c))

If you want to make a copy of a string, I recommend to desing your own
'strdup()' function:

#include <string.h>
#include <stdlib.h>

char *str_dup (char const * const s)
{
char *sdup;

if (s != NULL)
{
size_t size = strlen (s) + 1;

sdup = malloc (size);

if (sdup != NULL)
{
memcpy (sdup, s, size);
}
}
return sdup;
}

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #7


Emmanuel Delahaye wrote:
If you want to make a copy of a string, I recommend to desing your own
'strdup()' function:

#include <string.h>
#include <stdlib.h>

char *str_dup (char const * const s)
{
char *sdup;
To correct the flaw in the return value should the argument, s,
be a NULL value, make this:

char *sdup = NULL;

if (s != NULL)
{
size_t size = strlen (s) + 1;

sdup = malloc (size);

if (sdup != NULL)
{
memcpy (sdup, s, size);
}
}
return sdup;
}


--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #8
"Emmanuel Delahaye" <em**********@noos.fr> wrote in message
news:Xn***************************@213.228.0.196.. .
In 'comp.lang.c', "bml" <le*****@yahoo.com> wrote:
char s1 = "this string";

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);

/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');

/* Why empty content of s2 print out here*/
Empty ? I'm not sure. I would have said 'undeterminated', due to the lack

of final 0.


That's probably why he added the otherwise useless memset() in the first
place ;-)
Nov 14 '05 #9
"Thomas Matthews" <Th*************************@sbcglobal.net> wrote in
message news:40**************@sbcglobal.net...

char * s2;
if (strlen(s1) < 30)
{
s2 = malloc(30);
}
else
{
s2 = malloc(strlen(s1) + 1);
}


Why do you need the first branch?
Nov 14 '05 #10


Peter Pichler wrote:
"Emmanuel Delahaye" <em**********@noos.fr> wrote in message
news:Xn***************************@213.228.0.196.. .
In 'comp.lang.c', "bml" <le*****@yahoo.com> wrote:

char s1 = "this string";

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);

/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0'); I would have written:
while(*s2++ = *s1++);
/* Why empty content of s2 print out here*/
Empty ? I'm not sure. I would have said 'undeterminated', due to the lack


of
final 0.

It does not lack the terminating 0
Look at what happens in the while loop--
*s1 is copied to *s2 before the test for *s1!=0
When *s1 is zero that zero is assigned to *s2 and _then_ the loop
stops.

That's probably why he added the otherwise useless memset() in the first
place ;-)

Roger
Nov 14 '05 #11
"Bliss" <bl***@ic.mesh> wrote in message
news:10***************@netrek.net...
Peter Pichler wrote:
"Emmanuel Delahaye" <em**********@noos.fr> wrote:
In 'comp.lang.c', "bml" <le*****@yahoo.com> wrote:

/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0'); I would have written:
while(*s2++ = *s1++);
/* Why empty content of s2 print out here*/

Empty ? I'm not sure. I would have said 'undeterminated', due to the lackof final 0. It does not lack the terminating 0
Look at what happens in the while loop--
*s1 is copied to *s2 before the test for *s1!=0
....after which, s1 and s2 get incremented, pointing beyond the terminating
0.
When *s1 is zero that zero is assigned to *s2 and _then_ the loop
stops.


....leaving both s1 and s2 pointing to a cabbage field.
That's probably why he added the otherwise useless memset() in the first
place ;-)


Ther OP had probably been experiencing these problems and insted of trying
to find the problem, he "fixed" it by adding the useless memset().

Peter
Nov 14 '05 #12
In 'comp.lang.c', Al Bowers <xa******@rapidsys.com> wrote:
char *str_dup (char const * const s)
{
char *sdup;


To correct the flaw in the return value should the argument, s,
be a NULL value, make this:

char *sdup = NULL;


Absolutely. (Too fast typing).

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #13
Peter Pichler wrote:
"Thomas Matthews" <Th*************************@sbcglobal.net> wrote in
message news:40**************@sbcglobal.net...
char * s2;
if (strlen(s1) < 30)
{
s2 = malloc(30);
}
else
{
s2 = malloc(strlen(s1) + 1);
}

Why do you need the first branch?


Just to show the OP that the string overflowed the original
allocated length.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 14 '05 #14

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

Similar topics

22
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; ...
16
by: Khuong Dinh Pham | last post by:
I have the contents of an image of type std::string. How can I make a CxImage object with this type. The parameters to CxImage is: CxImage(byte* data, DWORD size) Thx in advance
4
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where...
19
by: Paul | last post by:
hi, there, for example, char *mystr="##this is##a examp#le"; I want to replace all the "##" in mystr with "****". How can I do this? I checked all the string functions in C, but did not...
12
by: Dave Bailey | last post by:
I need to store an encrypted connection string in the web.config file. I have found several examples on the Net but nothing specific as to how to accomplish task. Thanks in advance, Dave
32
by: Tubs | last post by:
Am i missing something or does the .Net Framework have a quirk in the way methods work on an object. In C++ MFC, if i have a CString and i use the format method, i format the string i am using. ...
12
by: CMirandaman | last post by:
Sounds like a stupid question I know. I can tell that they are used to copy strings. But what is the difference between x = y; versus x = String.Copy(y); Or are they essentially the same?
5
by: Martin Jørgensen | last post by:
Hello again, Sorry to bother but I guess my C++ book isn't very good since it obviously contains errors so the program code doesn't work with g++. However I don't understand what the problem...
6
by: Erik | last post by:
Hello, For many years ago I implemented my own string buffer class, which works fine except assignments - it copies the char* buffer instead of the pointer. Therefore in function calls I pass...
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 *...
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: 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...
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...

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.