473,763 Members | 1,312 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 15693
"*m½Z" <to****@world.c om> wrote in message
news:bu******** **@news.seed.ne t.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.c om> wrote in message
news:bu******** **@news.seed.ne t.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_st r,source_str,MA X_LEN_OF_DEST_S TR);
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,s ource,0,count) is equivalent to
strncpy(dest,so urce,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.c om> 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.c om> 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********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #5
"CBFalconer " <cb********@yah oo.com> wrote in message
news:40******** *******@yahoo.c om...
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********@yah oo.com> wrote in message
news:40******** *******@yahoo.c om...
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********@yah oo.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********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #8
CBFalconer <cb********@yah oo.com> wrote in message news:<40******* ********@yahoo. com>...
Peter Pichler wrote:
"CBFalconer " <cb********@yah oo.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********@yah oo.com> wrote:
Richard Bos wrote:
"*m½Z" <to****@world.c om> 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

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

Similar topics

0
2594
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 long search processes with a flush after each search. When i Navigate to the page, redirect to it from another page, or type the URL to this page in the browser, the page is buffered until it reaches the end of the file and is then displayed all at...
2
2094
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 * from table" and fetching all the records and displaying... It display all the data except data from this
4
1636
by: Developwebsites | last post by:
#ifndef PERSON_H #define PERSON_H #include<iostream> #include<iomanip> #include<string> class Person { protected: char name;
1
2533
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 ( 255 ); SELECT DISTINCT MyField AS Result FROM tb_Client;
3
7221
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 also setting the autopostback property to true for the dropdown list and it works but the handler doesnt get invoked at runtime... I have to do it in itemdatabound becaz whether to add the handler or not is driven based on the information which i...
8
7837
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 VALUE ENTERED BY THE USER EXISTS IN THE DB , then THE ERROR MESSAGE OF THE COMPARE VALIDATOR SHOULD BE DISPLAYED. For this, I used the reference artiicle "http://msdn.microsoft.com/library/default.asp?url=/library/en-...
3
2168
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 from an aspx file. Even a page with <%@ Page Language = "c#" Trace="True" %> doesnt show the trace information. If i create an .asp file, the server side code between <% %> will process and display correctly on the page.
0
1644
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 application by pressing run button. but it doesnt work when we type the path directly in the browser's address bar eg. http://localhost/testapplicationdefault.aspx error it gives is "COULD NOT LOAD testapplication._default". IN default.aspx. While in...
3
2983
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 imiedietely after i insert value into session1... is there any other way to do it? insert into 2 tables at the same time ...? if(!($sessid)){ session_register('sessid'); mysql_query("insert into session1 set sessid=null,
0
9386
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
9998
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...
0
9822
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...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
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
6642
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
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.