468,765 Members | 1,198 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,765 developers. It's quick & easy.

strncpy copying beyond max length

I am quite new to C++ and am haveing dificulty with the strncpy
function. I wrote this peice of code but the output I get from the
destination string after the copy is not what I expected, instead it
leaks into the memory space of string 1. Here is the output and the
code, Im hopeing someone can point me in the correct direction to solve
this problem:

const int MAX_STRING = 5;
char str1[] = "Hello, world!";
char str2[MAX_STRING+1]; // include room for null
strncpy(str2, str1, MAX_STRING);
cout << "String1: " << str1 << endl;
cout << "String2: " << str2 << endl;

output: Hello -w 3-wHello, world!

I was wanting to set string 2 to Hello but instead I got much more then
5 characters.

Jul 23 '05 #1
4 1316
at******@gmail.com wrote:

I was wanting to set string 2 to Hello but instead I got much more then
5 characters.


strncpy only copied five characters. There's a catch, though. Read the
documentation for strncpy carefully.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #2
Thanks, I have located the documentation and read it carfully and I can
now see the problem is a null was not appended because the value was
shorter then the length of the string being copyed thus i must apend my
own terminateing null caracter.

Much apreciation for this, I will read the documentation first for now
on. My book stated that it apends the null for me and I guess I asumed
this to be corect.

Problem solved.

Jul 23 '05 #3
at******@gmail.com wrote:

My book stated that it apends the null for me and I guess I asumed
this to be corect.


Sounds like a good book to get rid of. <g>

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #4
If you really want to use C++ properly, you should generally learn to use
string objects instead of char arrays. All these problems you are having
with string length and null termination are handled in a completely
transparent fashion by the standard C++ string class. Sounds nice doesn't
it? 8*)

HTH,

Dave Moore
Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by dbuser | last post: by
9 posts views Thread by fybar | last post: by
27 posts views Thread by Shagy | last post: by
53 posts views Thread by SK | last post: by
12 posts views Thread by anars | last post: by
43 posts views Thread by Frodo Baggins | last post: by
4 posts views Thread by chikito.chikito | last post: by
4 posts views Thread by lurch132002 | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.