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

Why strncpy(s, t, n) doesn't put '\0' at the end?

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);
.....
work just what I want.

Nov 14 '05 #1
12 15586
"*m½Z" <to****@world.com> wrote in message
news:bu**********@news.seed.net.tw...
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);
....
work just what I want.


It depends on how long the source string is. strncpy() copies up to n
characters from t into s. If t is shorter than n characters, remaining
characters in s are filled with zeros. If t is n characters long or longer,
the first n characters are copied and that's it. All of this is explained in
our manual. Have you read it first?

Peter
Nov 14 '05 #2

"*m½Z" <to****@world.com> wrote in message
news:bu**********@news.seed.net.tw...
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);
....
work just what I want.


Thats just the way it works. If count is less than the length of the
source string then you must null terminate yourself with:

dest_str[count]='\0';

If count is greater than the length of the source string then the
destination string will be padded with 0s up to count. But you can still
do the dest_str[count]='\0' (it is just redundant in this case).

strncpy() is useful for ensuring that you never exceed the length of a
string (causing a crash), and you should always use it if the source string
could be longer than the destination string (or if you are not sure). If
the source string was longer then the destination string will not be
automatically null terminated so you should put a '\0' at the end yourself
as follows:

strncpy(dest_str,source_str,MAX_LEN_OF_DEST_STR);
dest_str[MAX_LEN_OF_DEST_STR]='\0';

If the source string was shorter that the destination string, the dest str
will already be NULL terminated and the second line will be redudant (but so
what!).

NOTE that _memccpy(dest,source,0,count) is equivalent to
strncpy(dest,source,count) but is generally much faster (at least on a
Windows platform compiling with Borland or Microsoft compilers).

Hope this helps...

Sean

Nov 14 '05 #3
"*m½Z" <to****@world.com> wrote:
I am a C programming beginner...
I wonder, why strncpy(s, t, n) does not put '\0' at the end of the string.
Historical reasons. Originally, strncpy() was intended to work with a
particular kind of fixed length, null-padded, not necessarily null-
terminated char array, not with ordinary C strings at all.
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??


What strncpy() does is copy as much of the source into the destination
as required, but if the source is smaller than the limit, pad the rest
with null characters. That means, of course, that the result will happen
to be null-terminated as well; but it's also quite likely that it will
have written more nulls than necessary.

It's often better to use strncat() instead of strncpy(), if only for
efficiency; instead of

strncpy(dest, src, n);
dest[n]='\0';

you can use

*dest='\0';
strncat(dest, src, n);

which will _also_ result in at most n characters, null-terminated, being
written to dest, but will not have written all those extra null
characters if src is short.

Richard
Nov 14 '05 #4
Richard Bos wrote:
"*m½Z" <to****@world.com> wrote:
I am a C programming beginner...
I wonder, why strncpy(s, t, n) does not put '\0' at the end of

the string.

Historical reasons. Originally, strncpy() was intended to work with
a particular kind of fixed length, null-padded, not necessarily
null-terminated char array, not with ordinary C strings at all.
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??


What strncpy() does is copy as much of the source into the destination
as required, but if the source is smaller than the limit, pad the rest
with null characters. That means, of course, that the result will
happen to be null-terminated as well; but it's also quite likely that
it will have written more nulls than necessary.


Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';

You could encapsulate this in a macro. What it costs is the time
spent to nul fill the destination on each call.

#define STRNCPY(dst, src, n) \
do {strncpy((dst), (src), (n)-1); dst[(n)] = '\0';} while (0)

and dst and n expressions should not have side effects.

A better solution IMO is to use strlcpy and strlcat, which are NOT
standard. You can find an implementation on my pages, download
section.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #5
"CBFalconer" <cb********@yahoo.com> wrote in message
news:40***************@yahoo.com...
Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';


ITYM
strncpy(dst, src, n); dst[n-1] = '\0'; /* copies one char too many */
or
strncpy(dst, src, n); dst[n] = '\0'; /* or n-1, depending on n */

IMO,
strncpy(dst, src, n)[n] = '\0';
is better. It's even syntactically safe.
Nov 14 '05 #6
Peter Pichler wrote:

"CBFalconer" <cb********@yahoo.com> wrote in message
news:40***************@yahoo.com...
Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';


ITYM
strncpy(dst, src, n); dst[n-1] = '\0'; /* copies one char too many */
or
strncpy(dst, src, n); dst[n] = '\0'; /* or n-1, depending on n */

IMO,
strncpy(dst, src, n)[n] = '\0';
is better. It's even syntactically safe.


Not so. Given the array dst[10] the element dst[10] does not exist.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #7
Peter Pichler wrote:
"CBFalconer" <cb********@yahoo.com> wrote in message
Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';
ITYM
strncpy(dst, src, n); dst[n-1] = '\0'; /* copies one char too many */
or
strncpy(dst, src, n); dst[n] = '\0'; /* or n-1, depending on n */


You have at least a point or two. Mea sloppy. Note to self:
check boundary conditions.

IMO,
strncpy(dst, src, n)[n] = '\0';
is better. It's even syntactically safe.


Hey, that's sorta cute. Obfuscated, but cute. Maybe even:

*(n + strncpy(dst, src, n)) = 0;
or
n[strncpy(dst, src, n)] = 0;
or
/* for dst of type array, not char * */
/* This one may actually have some use !! */
#define STRZCPY(dst, src) /
(((sizeof dst)-1)[strncpy(dst, src, sizeof dst)] = 0);

(WARN: newbies should not listen to this obscure maundering)

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #8
CBFalconer <cb********@yahoo.com> wrote in message news:<40***************@yahoo.com>...
Peter Pichler wrote:
"CBFalconer" <cb********@yahoo.com> wrote in message
Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';


ITYM
strncpy(dst, src, n); dst[n-1] = '\0'; /* copies one char too many */
or
strncpy(dst, src, n); dst[n] = '\0'; /* or n-1, depending on n */


You have at least a point or two. Mea sloppy. Note to self:
check boundary conditions.

IMO,
strncpy(dst, src, n)[n] = '\0';
is better. It's even syntactically safe.


Great!, How about

#define STRNCPY(dst, src, n) (strncpy(dst, src, n)[n] = 0, dst)

?

- Satyajit Rai
Nov 14 '05 #9
CBFalconer <cb********@yahoo.com> wrote:
Richard Bos wrote:
"*m½Z" <to****@world.com> wrote:

What strncpy() does is copy as much of the source into the destination
as required, but if the source is smaller than the limit, pad the rest
with null characters. That means, of course, that the result will
happen to be null-terminated as well; but it's also quite likely that
it will have written more nulls than necessary.
Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';

You could encapsulate this in a macro. What it costs is the time
spent to nul fill the destination on each call.


Well, yes. That's why. On a single call that may seem trivial, but the
total cost of a lot of strncpy() calls can be significant.
#define STRNCPY(dst, src, n) \
do {strncpy((dst), (src), (n)-1); dst[(n)] = '\0';} while (0)

and dst and n expressions should not have side effects.

A better solution IMO is to use strlcpy and strlcat, which are NOT
standard.


Why use a non-Standard solution when

dest[0]='\0'; strncat(dest, src, n);

works just as well?

Richard
Nov 14 '05 #10
"Joe Wright" <jo********@earthlink.net> wrote in message
news:40***********@earthlink.net...
Peter Pichler wrote:
"CBFalconer" <cb********@yahoo.com> wrote in message
news:40***************@yahoo.com...
Why not simply write:

strncpy(dst, src, n-1); dst[n] = '\0';
ITYM
strncpy(dst, src, n); dst[n-1] = '\0'; /* copies one char too many */ or
strncpy(dst, src, n); dst[n] = '\0'; /* or n-1, depending on n

*/
Not so. Given the array dst[10] the element dst[10] does not exist.


In that case, n == 9. That's why I said, "depending on n".
Nov 14 '05 #11
CBFalconer <cb********@yahoo.com> wrote:
Richard Bos wrote:
Why use a non-Standard solution when

dest[0]='\0'; strncat(dest, src, n);

works just as well?
Because you have to pay peculiar attention to the value of n,


Peculiar? What's so unusual about having to know the length of the
memory area you're copying into? You _have_ to pass this length, or else
you're back with plain strcpy().
and the result doesn't tell you when something has been truncated.


That isn't always something you care about; and in any case, the
original strncpy() call doesn't give you that information, either.

Richard
Nov 14 '05 #12
Richard Bos wrote:

CBFalconer <cb********@yahoo.com> wrote:
Richard Bos wrote:
Why use a non-Standard solution when

dest[0]='\0'; strncat(dest, src, n);

works just as well?


Because you have to pay peculiar attention to the value of n,


Peculiar? What's so unusual about having to know the length of the
memory area you're copying into? You _have_ to pass this length, or else
you're back with plain strcpy().
and the result doesn't tell you when something has been truncated.


That isn't always something you care about; and in any case, the
original strncpy() call doesn't give you that information, either.


Then go right ahead and use it. I really don't mind. I don't
want to have to think about things, so the more natural the
parameters are the better. The more info I get back the better,
as long as it isn't misleading info.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #13

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

Similar topics

0
by: Copa | last post by:
Hello, I am testing buffering an asp page and Flushing information out to the browser, hence i wrote the code in an asp page that follows this Message Post. The loops are suppose to simulate...
2
by: dave | last post by:
Hi I m facing strange problem... I have one field char type data length 1.. It has data either 1 or 2 in all the field tht I have checked through enterprise manager. I'm running query "select...
4
by: Developwebsites | last post by:
#ifndef PERSON_H #define PERSON_H #include<iostream> #include<iomanip> #include<string> class Person { protected: char name;
1
by: Station Media | last post by:
Hi, here my problem, i use stored procedure in ACCESS database(latest version), and i would like to use this procedure but it doesnt work, do you know why ? Procedure: PARAMETERS MyField Text...
3
by: Clouds | last post by:
Hi ! How do I add the dynamic event handler for a dropdownlist present in the itemtemplate of a datalist !! I am doing it in the itemdatabound event of the datalist but it doesnt work... I am...
8
by: pmud | last post by:
Hi, I am using a compare validator in asp.net application(c# code). This Custom validator is used for comparing a value enterd by the user against the primary key in the SQL database. IF the...
3
by: Bruno Paquette | last post by:
I have installed visual studio .net and now i started to write the first few examples from the 70-315 book by Kalani. It looks like all server side code that i put between <% %> doesnt process...
0
by: Juna | last post by:
I have been working in vs2003, but now started to work in vs2005 but the problem, I have simple web application not website, which work i mean open in browser when we press F5 or run the...
3
by: jx2 | last post by:
hi guys i would appriciate your coments on this code - when i ran it for the very first time it doesnt see @last = LAST_INSERT_ID() but when i ran it next time it read it properly i need to know it...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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...
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.