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

strcpy question

The following code causes "Segementation fault":

char *s1;
char *s2;

s2 = "HELLO";

strcpy(s1, s2);

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?

Thanks.

Jun 1 '06 #1
9 2561
In article <11*********************@y43g2000cwc.googlegroups. com>,
Jack <ju******@gmail.com> wrote:
The following code causes "Segementation fault": char *s1;
char *s2; s2 = "HELLO"; strcpy(s1, s2);
You have declared s1 to be a pointer, but you haven't given it
any memory to point to.

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?


Not necessarily. For example,

char s1[128];
char *s2 = "HELLO";
if (strlen(s2) => sizeof s1) fprintf(stderr, "Opps, s2 is too long\n")
else strcpy(s1,s2);

The key is that the destination storage must exist before you can write
into it. malloc() is one way of getting that storage, but you can also
write into auto or static variables as long as you make sure you do
not write past the end of the variable.
--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)
Jun 1 '06 #2
Jack said:
The following code causes "Segementation fault":

char *s1;
char *s2;

s2 = "HELLO";

strcpy(s1, s2);
Yeah, it would.
If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));
s1 = malloc(strlen(s2) + 1);
if(s1 != NULL)
{
strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?


Yeah. Everything Has To Be Somewhere. You have to have somewhere to put it,
before you can put it there.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 1 '06 #3


Jack wrote On 06/01/06 16:28,:
The following code causes "Segementation fault":

char *s1;
char *s2;

s2 = "HELLO";

strcpy(s1, s2);

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?


See Questions 7.1, 7.2, and 7.3b in the comp.lang.c
Frequently Asked Questions (FAQ) list

http://www.c-faq.com/

--
Er*********@sun.com

Jun 1 '06 #4
"Jack" <ju******@gmail.com> writes:
The following code causes "Segementation fault":

char *s1;
char *s2;

s2 = "HELLO";

strcpy(s1, s2);

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?


Yes, of course.

Another point: the line
s1 = (char*)malloc(10 * sizeof(char));
is better written as
s1 = malloc(10);
Casting the result of malloc() is unnecessary and can mask errors.
sizeof(char) is 1 by definition.

(And, if you haven't already, please read
<http://cfaj.freeshell.org/google/>.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 1 '06 #5
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <11*********************@y43g2000cwc.googlegroups. com>,
Jack <ju******@gmail.com> wrote:

[...]
If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?


Not necessarily. For example,

char s1[128];
char *s2 = "HELLO";
if (strlen(s2) => sizeof s1) fprintf(stderr, "Opps, s2 is too long\n")
else strcpy(s1,s2);

The key is that the destination storage must exist before you can write
into it. malloc() is one way of getting that storage, but you can also
write into auto or static variables as long as you make sure you do
not write past the end of the variable.


I assumed that declaring s1 as an array object qualifies as
"allocating memory", but it's an important distinction. The memory
has to exist; how it's allocated is another question.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 1 '06 #6
Jack wrote:
.... snip ...
The code works well. So I should always allocate memory for s1,
before I call strcpy, right?


When you pour a glass of milk (beer, wine, water, etc.) I hope you
usually provide a glass to hold the poured substance.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Jun 1 '06 #7
Jack posted:
The following code causes "Segementation fault":

char *s1;
char *s2;

When you define a variable within a function without initialising it, it
contains white noise -- a bit-pattern left over from the last time that
memory was used. (Except if the object is static... but I won't get into
that just now).

An int variable holds an integer numerical value.

A pointer variable holds a memory address.

You define "s1" without initialising it -- as far as you're concerned, it
contains a random value. For the purpose of this demonstration, let's
assume that this "random memory address" is 2349538.

You also define "s2" without initialising it, but that's okay because you
set its value soon after.

s2 = "HELLO";

"s2" now contains the memory address of the first char in that string
literal. (I would advocate using pointer-to-const for this purpose).

strcpy(s1, s2);

You copy the string located at the memory address specified by s2 to the
memory address specified by s1. So basically you're copying "Hello" to
our random memory address of 2349538.

The memory address 2349538 isn't yours to access -- it could contain
important data.

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

Here you allocate 10 bytes of memory.

You then set the value of "s1" to the address of the first byte.

"s1" no longer contains a random value -- it contains a legitimate value;
you allocated those 10 bytes, and now you're free to use them in whatever
way you please.

strcpy(s1, s2);

Here you copy "Hello" to the address specified by "s1". The address
specified by "s1" is the 10 bytes of memory you allocated. This is fine.

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?

I find it handy to repeat to yourself, "A pointer stores a memory
address".

If you're going to be accessing the data stored at a memory address, you
must make sure you are allowed access the memory in question.
-Tomás
Jun 2 '06 #8

Jack wrote:
The following code causes "Segementation fault":

char *s1;
char *s2;

s2 = "HELLO";

strcpy(s1, s2);

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?

Thanks.

Yes you have to. there must be memory and has to be large enough to
hold the value.

Jun 2 '06 #9
Jack wrote:
The following code causes "Segementation fault":

char *s1;
char *s2;

s2 = "HELLO";

strcpy(s1, s2);

If I modify the code to:

char *s1;
char *s2;

s2 = "HELLO";

s1 = (char*)malloc(10 * sizeof(char));

strcpy(s1, s2);

The code works well. So I should always allocate memory for s1, before
I call strcpy, right?


You should always set any pointer to a valid region of memory or other
data structure before any operations upon it. In the meantime, you can
make it a null pointer.

Jun 2 '06 #10

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

Similar topics

7
by: Paul Sheer | last post by:
I need to automatically search and replace all fixed size buffer strcpy's with strncpy's (or better yet, strlcpy's) as a security and stability audit. The code base is large and it is not feasable...
23
by: JC | last post by:
hi, i want to combine two string together.. and put in to another string. how can i do . i try myself.. with the follow code. but seem can't get the result i want.. i want to get the result with...
8
by: herrcho | last post by:
#include <stdio.h> #include <string.h> int main() { char *imsip; strcpy(imsip, "archie"); return 0; }
10
by: ios | last post by:
Hi Can someone tell me what is different between below case? strcpy(eventname, "MDCX_RSP"); and sprintf(eventname, "MDCX_RSP"); Thanks, Leon
9
by: Pascal Damian | last post by:
I read somewhere that strcpy() is safer when dealing with malloc()-ed strings. Is that true? (Of course I know that both are unsafe). -- Pascal
3
by: nirvana4lf | last post by:
this is probably a noob question but wutever. im using the strcpy(); function but it isnt working. here is an example: #include <stdio.h> #include <iostream> #include <string> #include...
302
by: Lee | last post by:
Hi Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). Is this due to the possibility of array overflow? Is it correct that the program...
55
by: Jake Thompson | last post by:
I need to copy a value into a char * field. I am currently doing this strcpy(cm8link.type,"13"); but I get an error of error C2664: 'strcpy' : cannot convert parameter 1 from 'const char'...
4
by: chikito.chikito | last post by:
1. Can someone tell me the difference between these two functions: void strcpy(char *s1, const char *s2) { while(*s1++ = *s2++) ; } //function prototype of strcpy follows char...
16
by: mdh | last post by:
I have a question about the library function strcpy. In K&R on page 109, strcpy is used to copy a line ( line ) to a pointer (char *), which is first allocated space by K&Rs "alloc" function. In...
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:
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...
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...
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
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...
0
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...

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.