473,765 Members | 1,957 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

library implementation strncpy() modifies string literal, legal? more doubts need more suggestion?

1. In the following code, is the code (line 11) legal? Is there a
notice in the document to tell callers that the parameter s1 should
receive an array variable, i.e. type char[], but not a variable of char
*? p1 and p2 point to the same things but they must be declared as
different types? Is it nature?

char p1[] = "hello12345 6";
char *p2 = "world";
strncpy(p1, p2, strlen(p2));

And is the lack of the const keyword in the declaration of the
parameter s1 (line 2) an indication that s1 receives an argument of
array?
2. The temporary variable os1 (line 4) is used only once as the return
value (line 12). Is it better to use os1 instead of s1 throughout the
function except the declaration (line 4). Or just don't introduce the
temporary os1, is it also a good idea? Which style do you prefer?

/*from:
http://cvs.opensolaris.org/source/xr...til/string.c*/
char *
strncpy(char *s1, const char *s2, size_t n) /*line 2*/
{
char *os1 = s1; /*line 4*/

n++;
while (--n != 0 && (*s1++ = *s2++) != '\0')
;
if (n != 0)
while (--n != 0)
*s1++ = '\0'; /*line 11*/
return (os1); /*line 12*/
}
--
lovecreatesbeau ty

Jun 13 '06 #1
17 3056
lovecreatesbeau ty wrote:
Subject: library implementation strncpy() modifies string literal, legal?
It's perfectly legal for an implementation to do whatever it wants, so
long
as it forfills the required semantics of the C standard [assuming the
implementation claims conformance.]
more doubts need more suggestion?


If it hasn't been suggested to you before, then I'll suggest it to you
now:

Read the FAQ.

http://c-faq.com/

e.g...

http://c-faq.com/decl/strlitinit.html

The strncpy function is allowed to modify the string pointed to by the
first argument because that is what it is _supposed_ to do.

String literals have const[] type, but are non-modifiable (for
hysterical
reasons, as the saying goes...)

<snip>

--
Peter

Jun 13 '06 #2
lovecreatesbeau ty said:
1. In the following code, is the code (line 11) legal? Is there a
notice in the document to tell callers that the parameter s1 should
receive an array variable, i.e. type char[], but not a variable of char
*? p1 and p2 point to the same things but they must be declared as
different types? Is it nature?

char p1[] = "hello12345 6";
char *p2 = "world";
strncpy(p1, p2, strlen(p2));
Legal but often unwise. Note that p1[] now has the contents "world12345 6",
not just "world".
And is the lack of the const keyword in the declaration of the
parameter s1 (line 2) an indication that s1 receives an argument of
array?
No. It means that the function requires to be able to write to the n
characters starting at the address indicated by s1, so you'd better make
sure it can.
2. The temporary variable os1 (line 4) is used only once as the return
value (line 12). Is it better to use os1 instead of s1 throughout the
function except the declaration (line 4). Or just don't introduce the
temporary os1, is it also a good idea? Which style do you prefer?


The Standard, rightly or wrongly, requires strncpy to return the pointer
value it receives in the first parameter. It also needs to move a pointer
along from that point if it is to achieve its goal. So either way, a copy
of that value has to be made. Which pointer is used for moving along the
array and which is used for storing the original value doesn't make an
ounce of difference.

You are given a photocopy which you can scribble on if you wish. You need to
scribble on it, but you also need to keep hold of an unscribbled copy. So
you photocopy the photocopy. This being programming, the copy is perfect.
You now have two copies - one for best, and one for scribbling on. Does it
matter which you use for which usage? Of course not. They are identical for
any practical purpose.

--
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 13 '06 #3

Peter Nilsson wrote:
lovecreatesbeau ty wrote:
Subject: library implementation strncpy() modifies string literal, legal?
It's perfectly legal for an implementation to do whatever it wants, so
long
as it forfills the required semantics of the C standard [assuming the
implementation claims conformance.]


I'm not doubting the behavior of modification, but doubting on its
implementation or interface. You could provide you expertise and be
more patient to others.
String literals have const[] type, but are non-modifiable (for
hysterical
reasons, as the saying goes...)


Don't you think the following 2 lines are modifying a string literal?

char *s = "hysterical ";
s[1] = 'H';
--
lovecreatesbeau ty

Jun 13 '06 #4

Richard Heathfield wrote:
No. It means that the function requires to be able to write to the n
characters starting at the address indicated by s1, so you'd better make
sure it can.
But the compiler can not prevent callers from doing this:

char *p1 = "hello12345 6"; /*char p1[] = "hello12345 6";*/
char *p2 = "world";
strncpy(p1, p2, strlen(p2));

It's no guaranty in the language to detect the bad behavior at
compiling time, or the illegal thing is allowed in the language itself.
Just a runtime undefined error left.
The Standard, rightly or wrongly, requires strncpy to return the pointer
value it receives in the first parameter. It also needs to move a pointer
along from that point if it is to achieve its goal. So either way, a copy
of that value has to be made. Which pointer is used for moving along the
array and which is used for storing the original value doesn't make an
ounce of difference.
Thank Richard, what you said is clear and helpful to me.
You are given a photocopy which you can scribble on if you wish. You need to
scribble on it, but you also need to keep hold of an unscribbled copy. So
you photocopy the photocopy. This being programming, the copy is perfect.
You now have two copies - one for best, and one for scribbling on. Does it
matter which you use for which usage? Of course not. They are identical for
any practical purpose.


Don't understand it much, could you be more detail?
--
lovecreatesbeau ty

Jun 13 '06 #5
lovecreatesbeau ty said:

Richard Heathfield wrote:
No. It means that the function requires to be able to write to the n
characters starting at the address indicated by s1, so you'd better make
sure it can.
But the compiler can not prevent callers from doing this:

char *p1 = "hello12345 6"; /*char p1[] = "hello12345 6";*/
char *p2 = "world";
strncpy(p1, p2, strlen(p2));


The compiler is not forbidden from preventing callers from doing that, but
in general it would, I think, be fairly hard to detect.
It's no guaranty in the language to detect the bad behavior at
compiling time, or the illegal thing is allowed in the language itself.
No, it's not *allowed*. It's just not *punished*...
Just a runtime undefined error left.


....until runtime, maybe.

--
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 13 '06 #6
lovecreatesbeau ty wrote:
.... snip ...
Don't you think the following 2 lines are modifying a string literal?

char *s = "hysterical ";
s[1] = 'H';


They are causing Undefined Behaviour.

--
Some informative links:
news:news.annou nce.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 13 '06 #7
Richard Heathfield wrote:
lovecreatesbeau ty said:

Richard Heathfield wrote:
No. It means that the function requires to be able to write to the n
characters starting at the address indicated by s1, so you'd better make
sure it can.


But the compiler can not prevent callers from doing this:

char *p1 = "hello12345 6"; /*char p1[] = "hello12345 6";*/
char *p2 = "world";
strncpy(p1, p2, strlen(p2));

The compiler is not forbidden from preventing callers from doing that, but
in general it would, I think, be fairly hard to detect.

It shouldn't be, C++ compilers tend to emit a nasty warning if you
assign a string literal to a char*. One of the things I find strange
about the C standard is this not requiring a diagnostic.

--
Ian Collins.
Jun 13 '06 #8
Ian Collins said:
Richard Heathfield wrote:
lovecreatesbeau ty said:

Richard Heathfield wrote:

No. It means that the function requires to be able to write to the n
character s starting at the address indicated by s1, so you'd better make
sure it can.

But the compiler can not prevent callers from doing this:

char *p1 = "hello12345 6"; /*char p1[] = "hello12345 6";*/
char *p2 = "world";
strncpy(p1 , p2, strlen(p2));

The compiler is not forbidden from preventing callers from doing that,
but in general it would, I think, be fairly hard to detect.

It shouldn't be, C++ compilers tend to emit a nasty warning if you
assign a string literal to a char*.


Oh, that's easy enough to detect. But because it's legal in C, that's why it
becomes hard to detect when that privilege is abused.
One of the things I find strange
about the C standard is this not requiring a diagnostic.


Alas, it's one of those stupid "mustn't break already-broken code" things,
which is also why we still have stupid stupid gets().

--
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 13 '06 #9
Richard Heathfield wrote:
Ian Collins said:
Richard Heathfield wrote:
lovecreatesbeau ty said:
Richard Heathfield wrote:

> No. It means that the function requires to be able to write to
> the n characters starting at the address indicated by s1, so
> you'd better make sure it can.

But the compiler can not prevent callers from doing this:

char *p1 = "hello12345 6"; /*char p1[] = "hello12345 6";*/
char *p2 = "world";
strncpy(p1, p2, strlen(p2));

The compiler is not forbidden from preventing callers from doing
that, but in general it would, I think, be fairly hard to detect.

It shouldn't be, C++ compilers tend to emit a nasty warning
if you assign a string literal to a char*.


Oh, that's easy enough to detect. But because it's legal in C,
that's why it becomes hard to detect when that privilege is
abused.
One of the things I find strange
about the C standard is this not requiring a diagnostic.


Alas, it's one of those stupid "mustn't break already-broken
code" things, which is also why we still have stupid stupid gets().


Historically, it wasn't broken code. It was just systems that
stored literals where they could be modified, and then programs
that did just that. Never mind that it drove the maintainers nuts.

It still can work, as shown by the following baby program on _some_
systems:

[1] c:\c\junk>cat junk.c
#include <stdio.h>

int main(void)
{
char *junk = "Original";

puts(junk);
junk[0] = 'o';
puts(junk);
return 0;
}

[1] c:\c\junk>gcc -W -Wall -ansi -pedantic junk.c

[1] c:\c\junk>.\a
Original
original

The way to catch it is to add "-Wwrite-strings" to the gcc call,
although the error warning can be confusing.

--
Some informative links:
news:news.annou nce.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 13 '06 #10

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

Similar topics

16
17475
by: Don Starr | last post by:
When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer? For example, assuming a char is 1 byte and a char * is 4 bytes, should the following yield 4, 5, of something else? (And, if something else, what determines the result?) char x = "abcd"; printf( "%d\n", sizeof( x ) ); -Don
5
2720
by: Michael Hiegemann | last post by:
Hello, I am unaware whether this is the right group to ask. Please point me to another forum if required. I would like to replace a Fortran function by one which is written in C. The function shall provide the same interface for the fortran code calling the library. Fortunately, this works - currently under WinNT - well for all functions which do not return a string, e.g.
12
15694
by: ­m½Z | last post by:
I am a C programming beginner... I wonder, why strncpy(s, t, n) does not put '\0' at the end of the string. Because when I output the copied string, it output more than what I want, until I put '\0' at the end by myself. But, sometime I don't need put '\0' and it work well?? Like strncpy(s, t, n); strcat(s, t1); .....
22
2086
by: jacob navia | last post by:
A function like strcpy takes now, two unbounded pointers. Unbounded pointers, i.e. pointers where there is no range information, have catastrophic failure modes specially when *writing* to main memory. A better string library would accept *bounded* pointers. We would have then: char *strcpyN(char *destination, size_t bound1, char *src,size_t bound2);
8
3021
by: Robert A Riedel | last post by:
I have an application that requires a DLL and an executable that uses the DLL, both of which were implemented in Visual C++ using unmanged code. Both the executable and the DLL are linked with functions that are stored in a static library. During initialization of the executable, classes and static globals within functions linked from the static library appear to be initialized twice, once when the executable initializes the run-time code,...
6
4525
by: AlexD_UK | last post by:
When I create a new C++ project of type "Class Library (.NET)", I am unable to then add the following line of code : using namespace std If I do, I get the following error on compilation : c:\Research\Code\Visual Studio\TestC++2\TestC++2.h(7): error C2871: 'std' : a namespace with this name does not exist If I try this with other project types, e.g. "Console Application (.NET)" projects, I have no such problem.
87
5155
by: Robert Seacord | last post by:
The SEI has published CMU/SEI-2006-TR-006 "Specifications for Managed Strings" and released a "proof-of-concept" implementation of the managed string library. The specification, source code for the library, and other resources related to managed strings are available for download from the CERT web site at: http://www.cert.org/secure-coding/managedstring.html
0
3510
by: JosAH | last post by:
Greetings, welcome back; above we discussed the peripherals of the Library class: loading and saving such an instantiation of it, the BookMark interface and then some. This part of the article discusses the internals of the Library class a bit more. Sections again A previous article part showed how Sections work, i.e. a group Section refers to book Sections, a book Section refers to chapter Sections and the latter refer
9
3395
by: ssubbarayan | last post by:
Dear all, I am in the process of implementing pageup/pagedown feature in our consumer electronics project.The idea is to provide feature to the customers to that similar to viewing a single sms message in a mobile device.With in the given view area if the whole message does not fit,we need to provide the ability for users to scroll through the entire message using pageup/pagedown or key up and key down.In our case we have the whole...
0
9399
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10007
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
9955
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,...
0
9833
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7378
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
6649
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
5421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.